更改NSURL的计划

kam*_*ath 23 ios

有没有一种简单的方法来改变一个方案NSURL?我确实意识到这NSURL是不可改变的.我的目标是在链接时将URL的方案更改为"https" Security.framework,如果框架未链接则将"http" 更改为"http".我知道如何检测框架是否链接.

如果URL没有参数(例如"?param1 = foo¶m2 = bar"),此代码可以很好地工作:

+(NSURL*)adjustURL:(NSURL*)inURL toSecureConnection:(BOOL)inUseSecure {
    if ( inUseSecure ) {
        return [[[NSURL alloc] initWithScheme:@"https" host:[inURL host] path:[inURL path]] autorelease];
    }
    else {
        return [[[NSURL alloc] initWithScheme:@"http" host:[inURL host] path:[inURL path]] autorelease];
    }    
}
Run Code Online (Sandbox Code Playgroud)

但是,如果URL确实有参数,请[inURL path]删除它们.

任何建议都不能自己解析URL字符串(我可以做但我想尝试不做)?我做了什么能够将http或https的URL传递给此方法.

Lil*_*ard 45

更新的答案

NSURLComponents是你的朋友.您可以使用它来替换http方案https.唯一的警告是NSURLComponents使用RFC 3986,而NSURL使用较旧的RFC 1738和1808,因此在边缘情况下存在一些行为差异,但是你极不可能遇到这些情况(并且NSURLComponents无论如何都有更好的行为).

NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:YES];
components.scheme = inUseSecure ? @"https" : @"http";
return components.URL;
Run Code Online (Sandbox Code Playgroud)

原始答案

为什么不做一点字符串操作?

NSString *str = [url absoluteString];
NSInteger colon = [str rangeOfString:@":"].location;
if (colon != NSNotFound) { // wtf how would it be missing
    str = [str substringFromIndex:colon]; // strip off existing scheme
    if (inUseSecure) {
        str = [@"https" stringByAppendingString:str];
    } else {
        str = [@"http" stringByAppendingString:str];
    }
}
return [NSURL URLWithString:str];
Run Code Online (Sandbox Code Playgroud)

  • 把它放在一个类别中.:) (2认同)

onm*_*133 29

如果您使用的是iOS 7或更高版本,您可以使用NSURLComponents,作为显示在这里

NSURLComponents *components = [NSURLComponents new];
components.scheme = @"http";
components.host = @"joris.kluivers.nl";
components.path = @"/blog/2013/10/17/nsurlcomponents/";

NSURL *url = [components URL];
// url now equals:
// http://joris.kluivers.nl/blog/2013/10/17/nsurlcomponents/
Run Code Online (Sandbox Code Playgroud)

  • 我建议使用NSURLComponents*components = [NSURLComponents componentsWithURL:URL resolvingAgainstBaseURL:NO]; (2认同)

sla*_*los 5

斯威夫特5

extension URL {
    func settingScheme(_ value: String) -> URL {
    let components = NSURLComponents.init(url: self, resolvingAgainstBaseURL: true)
    components?.scheme = value
    return (components?.url!)!
}
Run Code Online (Sandbox Code Playgroud)

}

用法

if nil == url.scheme { url = url.settingScheme("file") }
Run Code Online (Sandbox Code Playgroud)