如何在URL中使用特殊字符\ n

时间:2017-04-06 08:54:52

标签: swift url post swift3

我有POST请求:

init (url: String,arg: String) {
    self.responseString = nil
    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "POST"
    let postString = arg
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) {
        data, response, error in
        guard let data = data, error == nil else {                                                 
            print("error=\(error)")
            self.responseString = nil
            return
        }
        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           //
            self.responseString = nil
        } else {
        self.responseString = String(data: data, encoding: .utf8)
        }
    }
    task.resume()
    }

当arg有一个字符\ n时,会丢失一半的arg文本。怎么解决这个问题?

1 个答案:

答案 0 :(得分:1)

strUrl = strUrl.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)!

let url = URL.init(string: strUrl)

let requestURL = URLRequest(url: url!)
  • 您需要添加addsPercentEncoding(withAllowedCharacters:CharacterSet.urlQueryAllowed)方法以允许URL查询。