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,852評論 3 24
  • 原文地址:swift4.0 適配 一、前言 在我們的工程中處于swift和OC混編的狀態,使用swift已經有一年...
    默默_David閱讀 1,949評論 0 3
  • 有的時候咱們會碰見字符串里有一些特殊字符在轉成URL的時候 會出現轉換不了的情況,這個時候需要對字符串進行編碼9....
    HOULI閱讀 236評論 0 0
  • URLEncode iOS 開發中請求訪問 Http(s) 時,必須對 URL 進行轉碼 (Encode),如果是...
    BlessNeo閱讀 1,555評論 0 0
  • @interfaceNSString (NSURLUtilities) // Returns a new stri...
    流沙3333閱讀 584評論 0 0