ios – 更改NSURL的方案
有沒有辦法改變NSURL的方案?我確實意識到NSURL是不變的.如果Security.framework被連結,我的目標是將URL的方案改為“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]會丟棄它們.
任何建議不足以自己解析URL字串(我可以做但我想嘗試不做)?我可以通過http或https傳遞URL到這個方法.
更新答案
NSURLComponents是您的朋友.您可以使用它來交換https的http方案.唯一的注意事項是NSURLComponents使用RFC 3986,而NSURL使用較舊的RFC 1738和1808,因此在邊緣情況下存在一些行為差異,但是您極不可能遇到這些情況(NSURLComponent的行為更好).
NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:YES]; components.scheme = inUseSecure ? @"https" : @"http"; return components.URL;
原來的答案
為什麼不做一點字串操作?
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];
程式碼日誌版權宣告:
翻譯自:http://stackoverflow.com/questions/14393016/change-a-nsurls-scheme