Swift - encode URL

后端 未结 17 1871
無奈伤痛
無奈伤痛 2020-11-21 22:20

If I encode a string like this:

var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

it does

17条回答
  •  梦如初夏
    2020-11-21 22:49

    Swift 3:

    let originalString = "http://www.ihtc.cc?name=htc&title=iOS开发工程师"
    

    1. encodingQuery:

    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters:NSCharacterSet.urlQueryAllowed)
    

    result:

    "http://www.ihtc.cc?name=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88" 
    

    2. encodingURL:

    let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)
    

    result:

    "http:%2F%2Fwww.ihtc.cc%3Fname=htc&title=iOS%E5%BC%80%E5%8F%91%E5%B7%A5%E7%A8%8B%E5%B8%88"
    

提交回复
热议问题