改变NSURL的计划 [英] Change a NSURL's scheme

查看:118
本文介绍了改变NSURL的计划的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there an easy way to change the scheme of a NSURL? I do realize that NSURL is immutable. My goal is to change the scheme of an URL to "https" if the Security.framework is linked, and "http" if the framework is not linked. I do know how to detect if the framework is linked.

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

This code works wonderfully if the URL has no parameters (such as "?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路径] 删除它们。

But if the URL does have parameters, [inURL path] drops them.

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

Any suggestions short of parsing the URL string myself (which I can do but I want to try not doing)? I do what to be able to pass URLs with either http or https to this method.

推荐答案

更新回答



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

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

这篇关于改变NSURL的计划的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆