无法从Google距离矩阵api获得响应

时间:2018-03-07 07:14:30

标签: ios google-maps-api-3 swift4 google-distancematrix-api

我正在使用谷歌距离矩阵API,我正在使用以下代码

        let headers: HTTPHeaders = [ "Accept": "application/json", "Content-Type": "application/json" ]

        let url = "https://maps.googleapis.com/maps/api/distancematrix/json?&origins=\(start)&destinations=\(end)&key=AIzaSyDvt_KiUCtdb1kPEw4E4Dt68EuiF8PosAg"

        let header: HTTPHeaders = [ "Accept": "application/json", "Content-Type": "application/json" ]

         Alamofire.request( url, method: .get, encoding: JSONEncoding.default, headers : header) .responseString {  response in

            print(response.request)  // original URL request
            print(response.response) // HTTP URL response
            print(response.data)     // server data
            print(response.result)


        }

根据这个Unable to fetch Response For Google Distance matrix in Swift我正在传递标题,但我仍然得到以下错误。 enter image description here

这是我的包含开头和结尾的网址  “https://maps.googleapis.com/maps/api/distancematrix/json?&origins=Nanpura,Surat,Gujarat 395008,India& destinations = Adajan,Surat,Gujarat,India& key = AIzaSyDvt_KiUCtdb1kPEw4E4Dt68EuiF8PosAg”

2 个答案:

答案 0 :(得分:2)

我检查了请求,它运行正常。我猜你错过了info.plist中的隐私设置

enter image description here

enter image description here

答案 1 :(得分:1)

您应该对网址进行编码,请尝试使用此

    let url = "https://maps.googleapis.com/maps/api/distancematrix/json?&origins=Nanpura, Surat, Gujarat 395008, India&destinations=Adajan, Surat, Gujarat, India&key=AIzaSyDvt_KiUCtdb1kPEw4E4Dt68EuiF8PosAg"
    let encodedUrl = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)

    let header: HTTPHeaders = [ "Accept": "application/json", "Content-Type": "application/json" ]

    Alamofire.request(encodedUrl! , method: .get,encoding: JSONEncoding.default, headers: header)
        .responseJSON { (data) in
            print(data)
    }

这也可行,

Alamofire.request(encodedUrl!, method: .get,encoding: JSONEncoding.default, headers: header)
            .responseString {response in
                print(response.request)  // original URL request
                print(response.response) // HTTP URL response
                print(response.data)     // server data
                print(response.result)
        }

响应将是这样的,

SUCCESS: {
    "destination_addresses" =     (
        "Adajan, Surat, Gujarat, India"
    );
    "origin_addresses" =     (
        "Nanpura, Surat, Gujarat 395008, India"
    );
    rows =     (
                {
            elements =             (
                                {
                    distance =                     {
                        text = "2.4 km";
                        value = 2433;
                    };
                    duration =                     {
                        text = "6 mins";
                        value = 373;
                    };
                    status = OK;
                }
            );
        }
    );
    status = OK;
}