使用 alamofire 的 https 请求失败

https request with alamofire fails

我对 swift 和编程还很陌生,所以这可能是个愚蠢的错误。无论如何,当我执行 url 请求声称 HTTPS_REQUIRED 时,我的代码失败了,尽管我的 url 字符串似乎没问题,即使我在浏览器中手动检查它

我试过在 plist 文件中添加 "App Transport Security Settings" 键,但也没有用。

func getImage(url : String){

    print(url)
    Alamofire.request(url, method: .get).responseJSON {
        response in
        if response.result.isSuccess {
            print(response.result.value)
        }
        else {
            print("Error \(response.result.error)")
            self.loadingLable.text = "Network Error"
        }
    }

}

//MARK:- Build the url request
func constructUrlRequest(latitude : String, longitude : String) {
    urlComponets.scheme = "https"
    urlComponets.host = "api.nasa.gov"
    urlComponets.path = "/planetary/earth/imagery"
    urlComponets.queryItems = [
        URLQueryItem(name : "lon", value : longitude),
        URLQueryItem(name : "lat", value : latitude),
        URLQueryItem(name: "api_key", value: "DEMO_KEY")
    ]
    let urlString = urlComponets.url?.absoluteString
    getImage(url: urlString!)

}

这是我的控制台输出:

longitude = -122.03051210999995, latitude = 37.33240904999999
https://api.nasa.gov/planetary/earth/imagery?lon=-122.03051210999995&lat=37.33240904999999&api_key=DEMO_KEY
Optional({
    error =     {
        code = "HTTPS_REQUIRED";
        message = "Requests must be made over HTTPS. Try accessing the API at: https://api.nasa.gov/planetary/earth/imagery/?lon=-122.03051210999995&lat=37.33240904999999&api_key=DEMO_KEY";
    };
})

你的代码是正确的,请求是在 https 中完成的,但是 NASA API 有点乱。

刚刚检查了 API documentation,它重定向到 /planetary/earth/imagery/,并且还需要请求中的其他变量。

试试这个:

   urlComponets.scheme = "https"
   urlComponets.host = "api.nasa.gov"
   urlComponets.path = "/planetary/earth/imagery/"
   urlComponets.queryItems = [
       URLQueryItem(name : "lon", value : "100.75"),
       URLQueryItem(name : "lat", value : "1.5"),
       URLQueryItem(name: "date", value: "2014-02-01"),
       URLQueryItem(name: "cloud_score", value: "True"),
       URLQueryItem(name: "api_key", value: "DEMO_KEY")
   ]

输出:

Optional({
    "cloud_score" = "0.03926652301686606";
    date = "2014-02-04T03:30:01";
    id = "LC8_L1T_TOA/LC81270592014035LGN00";
    resource =     {
        dataset = "LC8_L1T_TOA";
        planet = earth;
    };
    "service_version" = v1;
    url = "https://earthengine.googleapis.com/api/thumb?thumbid=bc77b079c8ecd07cd668c576c22b83a4&token=51a4298b6aae4529caee9ed0b64e636f";
})