如何使Http获取请求URL由swift 3中的管道组成?

时间:2017-08-04 08:46:25

标签: ios swift http-get

我有一个来自swift 3的get请求。该url有管道。没有管道它的工作正常,但是当我添加管道时,代码在解开可选值错误时打破说找到了nil。

这是我的网址 let url = URL(字符串:" 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 个答案:

答案 0 :(得分:2)

|不是网址中允许的字符。尝试百分比转义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()))