gpt4 book ai didi

ios - 如何使 Http get 请求 URL 由 swift 3 中的管道组成?

转载 作者:行者123 更新时间:2023-11-28 12:18:47 24 4
gpt4 key购买 nike

我从 swift 3 发出了一个获取请求。那个 url 有管道。没有管道它工作正常但是当我添加管道时代码中断说在展开可选值错误时发现 nil。

这是我的网址let 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
}

谁能告诉我为什么会这样?

最佳答案

| 不是 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()))

关于ios - 如何使 Http get 请求 URL 由 swift 3 中的管道组成?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45502195/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com