最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

【未解决】stringByAddingPercentEscapesUsingEncoding is deprecated Use stringByAddingPercentEncodingWithAllowedCharacters(_:) instead

Swift crifan 4146浏览 0评论

【问题】

将旧的swift代码,转换到最新的swift的语法:

        if let encoded = urlVal.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) {
            if let u = NSURL(string: encoded) {
                return self.requestSerializer.createRequest(u, method: method, parameters: parameters)
            }
        }

代码出错:

/Users/crifan/dev/dev_root/xxx/projects/xxx/ios/ios/ios/xxx/model/network/HTTPTask.swift:390:33: ‘stringByAddingPercentEscapesUsingEncoding’ is deprecated: Use 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.

如图:

stringByAddingPercentEscapesUsingEncoding is deprecated

 

【解决过程】

1.搜:

stringByAddingPercentEscapesUsingEncoding is deprecated Use stringByAddingPercentEncodingWithAllowedCharacters(_:) instead

参考:

Any plan to update to Xcode 7 with latest Swift syntax? · Issue #247 · SwiftyJSON/SwiftyJSON · GitHub

在吐槽,升级Xcode7之后,一堆新语法建议和转换,很是麻烦。

 

stringByAddingPercentEscapesUsingEncoding deprecated warning · Issue #311 · SwiftyJSON/SwiftyJSON · GitHub

ios – Replacement for stringByAddingPercentEscapesUsingEncoding in ios9? – Stack Overflow

算了,好像看不出啥就按照建议去修改吧。

2.直接替换:

        if let encoded = urlVal.stringByAddingPercentEncodingWithAllowedCharacters(NSUTF8StringEncoding) {

结果又出错:

HTTPTask.swift:390:84: Cannot convert value of type ‘UInt’ to expected argument type ‘NSCharacterSet’

Cannot convert value of type UInt to expected argument type NSCharacterSet

算了,去找找:

stringByAddingPercentEncodingWithAllowedCharacters

看看语法是啥,如何使用。

搜:

stringByAddingPercentEncodingWithAllowedCharacters

stringbyaddingpercentencodingwithallowedcharacters example

参考:

An example of populating a HTTPBody of NSMutableURLRequest for  GitHub

用法是:

        let characterSet = NSMutableCharacterSet.alphanumericCharacterSet()
        characterSet.addCharactersInString("-._~")
        return stringByAddingPercentEncodingWithAllowedCharacters(characterSet)

参考:

ios – How to encode a URL in Swift – Stack Overflow

和上面的:

ios – Replacement for stringByAddingPercentEscapesUsingEncoding in ios9? – Stack Overflow

应该改为:

        if let encoded = urlVal.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet()) {

期间,xcode中可以自动提示对应的函数和属性:

xcode auto complete  URLHostAllowedCharacterSet

不过修改之后,点击进去看看最新代码实现。

 

【总结】

后来,又暂时放下,不去折腾了。

有空再继续。

转载请注明:在路上 » 【未解决】stringByAddingPercentEscapesUsingEncoding is deprecated Use stringByAddingPercentEncodingWithAllowedCharacters(_:) instead

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
85 queries in 0.172 seconds, using 22.08MB memory