【问题】
将旧的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.
如图:
【解决过程】
1.搜:
stringByAddingPercentEscapesUsingEncoding is deprecated Use stringByAddingPercentEncodingWithAllowedCharacters(_:) instead
参考:
在吐槽,升级Xcode7之后,一堆新语法建议和转换,很是麻烦。
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’ |
算了,去找找:
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中可以自动提示对应的函数和属性:
不过修改之后,点击进去看看最新代码实现。
【总结】
后来,又暂时放下,不去折腾了。
有空再继续。
转载请注明:在路上 » 【未解决】stringByAddingPercentEscapesUsingEncoding is deprecated Use stringByAddingPercentEncodingWithAllowedCharacters(_:) instead