iOS swift urlencode

swift 升级到5,更新了三方库,支持的系统也从ios 8 升到了 ios 10 。
发现有很多方法过期了。
1.编码

func urlencode(_ string: String) -> String {
        let mstring = string.replacingOccurrences(of: " ", with: "+")
        let legalURLCharactersToBeEscaped: CFString = "!*'\"();:@&=+$,/?%#[]% " as CFString
        return CFURLCreateStringByAddingPercentEscapes(nil, mstring as CFString?, nil, legalURLCharactersToBeEscaped, CFStringBuiltInEncodings.UTF8.rawValue) as String
}

告警如下:
'CFURLCreateStringByAddingPercentEscapes' was deprecated in iOS 9.0: Use [NSString stringByAddingPercentEncodingWithAllowedCharacters:] instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent (since each URL component or subcomponent has different rules for what characters are valid).

修改方法:

func urlencode(_ string: String) -> String {
    let mstring = string.replacingOccurrences(of: " ", with: "+")
    let set = CharacterSet(charactersIn: "!*'\"();:@&=+$,/?%#[]% ")
    return mstring.addingPercentEncoding(withAllowedCharacters: set) ?? ""
}

charactersIn的内容和服务器沟通好,但在网上也找到了通用的封装

extension String {
     
    //将原始的url编码为合法的url
    func urlEncoded() -> String {
        let encodeUrlString = self.addingPercentEncoding(withAllowedCharacters:
            .urlQueryAllowed)
        return encodeUrlString ?? ""
    }
     
    //将编码后的url转换回原始的url
    func urlDecoded() -> String {
        return self.removingPercentEncoding ?? ""
    }
}

app内一顿测试,发现以上修改方法不行,很多特殊符号没有编译。
最终找到了目前经过很多特殊字符测试都通过的90%完美写法。

func urlencode(_ string: String) -> String {
    var allowedQueryParamAndKey = NSCharacterSet.urlQueryAllowed
    allowedQueryParamAndKey.remove(charactersIn: "!*'\"();:@&=+$,/?%#[]% ")
    return string.addingPercentEncoding(withAllowedCharacters: allowedQueryParamAndKey) ?? string
}

如果按你的理解认为这个上面代码是胡扯八道,其实你不防尝试一下。

最开始我搜索信息看到相关的代码的时候,我直接pass他,都是要加一些未被收录的字符,在这里删除那肯定是错误的,没想到让一个不会swift的安卓开发同事让尝试一下,为了让他死心,我一尝试,结果竟然是正确的,我目前也给不了一个合理的解析,这段代码就是能解决这个问题。

我们对应的后台用的是go技术,对应的解码是url.go中如下方法:

// QueryUnescape does the inverse transformation of QueryEscape,
// converting each 3-byte encoded substring of the form "%AB" into the
// hex-decoded byte 0xAB.
// It returns an error if any % is not followed by two hexadecimal
// digits.
func QueryUnescape(s string) (string, error) {
    return unescape(s, encodeQueryComponent)
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 在iOS 9.0之后,以前常用的NSString编码的方法stringByAddingPercentEscapes...
    Ro_bber阅读 16,941评论 3 24
  • 原文地址:swift4.0 适配 一、前言 在我们的工程中处于swift和OC混编的状态,使用swift已经有一年...
    默默_David阅读 1,967评论 0 3
  • 有的时候咱们会碰见字符串里有一些特殊字符在转成URL的时候 会出现转换不了的情况,这个时候需要对字符串进行编码9....
    HOULI阅读 241评论 0 0
  • URLEncode iOS 开发中请求访问 Http(s) 时,必须对 URL 进行转码 (Encode),如果是...
    BlessNeo阅读 1,557评论 0 0
  • @interfaceNSString (NSURLUtilities) // Returns a new stri...
    流沙3333阅读 620评论 0 0