改变一个NSURL的scheme

有没有简单的方法来改变NSURL的scheme? 我知道NSURL是不可变的。 我的目标是如果Security.framework被链接,则将URL的scheme更改为“https”;如果框架未链接,则更改“http”。 我知道如何检测框架是否链接。

如果URL没有参数(例如“?param1 = foo&param2 = 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]; } } 

但是如果URL确实有参数, [inURL path]会丢弃它们。

任何build议短的parsingURLstring我自己(我可以做,但我想尝试不做)? 我做了什么可以传递URL或HTTP或HTTPS到这个方法。

更新了答案

NSURLComponents在这里是你的朋友。 您可以使用它来换出httpshttpscheme。 唯一需要注意的是NSURLComponents使用RFC 3986,而NSURL使用较旧的RFC 1738和1808,所以在边缘情况下有一些行为差异,但是你不太可能遇到这种情况(而且NSURLComponents有更好的行为)。

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

原始答案

为什么不只是做一些string操作?

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

如果您使用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/ 

也许使用resourceSpecifier将有助于:

 return [[[NSURL alloc] initWithString:[NSString stringWithFormat:@"https:%@", [inURL resourceSpecifier]]]]; 

我在NSURL的类别中这样做了
从Apple文档

资源说明符。 (只读)声明

迅速

var resourceSpecifier:String? {get}

Objective-C的

@属性(只读,复制)NSString * resourceSpecifier讨论

该属性包含资源说明符。 例如,在URL http://www.example.com/index.html?key1=value1#jumplink中 ,资源说明符是//www.example.com/index.html?key1=value1#jumplink(之后的所有内容冒号)。

  -(NSURL*) URLByReplacingScheme { NSString *newUrlString = kHttpsScheme; if([self.scheme isEqualToString:kEmbeddedScheme]) newUrlString = kHttpScheme; newUrlString = [newUrlString stringByAppendingString:[NSString stringWithFormat:@":%@", self.resourceSpecifier]]; return [NSURL URLWithString:newUrlString]; } 
 NSString *newUrlString = [NSString stringWithFormat:@"https://%@%@", inURL.host, inURL.path]; if (inURL.query) { newUrlString = [newUrlString stringByAppendingFormat:@"?%@", inURL.query]; } return [NSURL URLWithString:newUrl]; 

[注意]与端口和其他字段处理有关的代码是简单的删除。