如何使 Http 获取请求 URL 由 swift 3 中的管道组成?
Posted
技术标签:
【中文标题】如何使 Http 获取请求 URL 由 swift 3 中的管道组成?【英文标题】:How to make Http get request URL consist of pipelines in swift 3? 【发布时间】:2017-08-04 08:46:24 【问题描述】:我从 swift 3 发出了一个获取请求。该 url 有管道。如果没有管道,它可以正常工作,但是当我添加管道时,代码中断说在展开可选值错误时发现 nil。
这是我的网址 让 url = URL(string:"https://maps.googleapis.com/maps/api/directions/json?origin=colombo&destination=kandy&waypoints=optimize:true|&key=AIzaSyCNBcQLIVvNwqjkYiLawnYK_AM")
这是我的代码:
func synchronusGetRequstForExternalAPI(api_url:String, headers:[ String: String]) -> ResultModel
let resultModel = ResultModel()
//create the url with URL
let url = URL(string:"https://maps.googleapis.com/maps/api/directions/json?origin=colombo&destination=kandy&waypoints=optimize:true|&key=AIzaSyCNBcQLIVvNwqjkYiLawnYK_OK4EQbRM5M")
//create the URLRequest object using the url object
var request = URLRequest(url: url!)
//set headers
for item in headers
request.addValue(item.value, forHTTPHeaderField: item.key)
let semaphore = DispatchSemaphore(value: 0)
let task = URLSession.shared.dataTask(with: request as URLRequest)
(data, response, error) in
if(error != nil)
resultModel.ErrorType = .NO_INT
resultModel.JsonReslut = JSON.null
else
if let resp = response as? HTTPURLResponse
if(resp.statusCode == 200)
if let jsonResult = JSON(data) as? JSON
resultModel.ErrorType = .NO_ERROR
resultModel.JsonReslut = jsonResult
else
if let jsonResult = JSON(data) as? JSON
resultModel.ErrorType = .SEREVR_ERROR
resultModel.JsonReslut = jsonResult
else
resultModel.ErrorType = .SEREVR_ERROR
resultModel.JsonReslut = JSON.null
semaphore.signal()
task.resume()
_ = semaphore.wait(timeout: DispatchTime.distantFuture)
return resultModel
谁能告诉我为什么会这样?
【问题讨论】:
【参考方案1】:|
不是 URL 中允许的字符。尝试百分比转义 URL 字符串
let url = URL(string:"https://maps.googleapis.com/maps/api/directions/json?origin=colombo&destination=kandy&waypoints=optimize:true|&key=AIzaSyCNBcQLIVvNwqjkYiLawnYK_OK4EQbRM5M".stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLFragmentAllowedCharacterSet()))
【讨论】:
以上是关于如何使 Http 获取请求 URL 由 swift 3 中的管道组成?的主要内容,如果未能解决你的问题,请参考以下文章
swift或OC中NSURLConnection finished with error - code -1002
Swift 获取 HTTP JSON 响应并使用 Codable 解析它
使用 alamofire 和 Swift4 IOS 获取 XML HTTP url 的响应