ios – 更改NSURL的方案

栏目: IOS · 发布时间: 7年前

内容简介:代码日志版权声明:翻译自:http://stackoverflow.com/questions/14393016/change-a-nsurls-scheme

有没有办法改变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


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Web Design Handbook

Web Design Handbook

Baeck, Philippe de 编 / 2009-12 / $ 22.54

This non-technical book brings together contemporary web design's latest and most original creative examples in the areas of services, media, blogs, contacts, links and jobs. It also traces the latest......一起来看看 《Web Design Handbook》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具