Change a NSURL's scheme Change a NSURL's scheme ios ios

Change a NSURL's scheme

Updated answer

NSURLComponents is your friend here. You can use it to swap out the http scheme for https. The only caveat is NSURLComponents uses RFC 3986 whereas NSURL uses the older RFCs 1738 and 1808, so there is some behavior differences in edge cases, but you're extremely unlikely to hit those cases (and NSURLComponents has the better behavior anyway).

NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:YES];components.scheme = inUseSecure ? @"https" : @"http";return components.URL;

Original answer

Why not just do a bit of string manipulation?

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];

If you are using iOS 7 and later, you can use NSURLComponents, as show here

NSURLComponents *components = [NSURLComponents new];components.scheme = @"http"; = @"";components.path = @"/blog/2013/10/17/nsurlcomponents/";NSURL *url = [components URL];// url now equals://


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



if nil == url.scheme { url = url.settingScheme("file") }