swift - alamofire 没有正确连接到 api

标签 swift alamofire

我正在尝试从 openweathermap api 获取包含 json 的响应, 但是从调试器看来,当他到达 alamofire 的代码块时,它只是跳过了它

这是我用于此任务的代码块

func printJson(){

    Alamofire.request("https://api.openweathermap.org/data/2.5/find?appid=6ad1f143546b8c6d761ecbda6a34a005&q=yavne", method: .get).responseJSON { response in
        if response.data != nil {
            var json : JSON
            do{
                json = try JSON(data: response.data!)
                print(json)
        }catch{}
        }

    }

}

最佳答案

使用这个辅助类进行 API 调用。

class NetworkHandler {

    static let shared = NetworkHandler()

    func sendRequest(withUrl url:String,andBody body:[String:Any]? = [:],
                         completionHandler: @escaping ((_ status: Bool,_ response:Any) -> Void)) {
        DispatchQueue.global(qos: .userInitiated).async {

            Alamofire.request(url, method: .post, parameters: body,encoding: JSONEncoding.default, headers: nil).responseJSON {
                response in

                guard response.response?.statusCode == 200 else{
                    completionHandler(false,"Service Temporarily Unavailable.\nPlease check your internet connection or  contact your Service provider.")
                    return
                }
                switch response.result {
                case .success:
                    completionHandler(true,response.value!)
                    break
                case .failure(let error):
                    completionHandler(false,error.localizedDescription)
                }
            }
        }
    }
}

关于swift - alamofire 没有正确连接到 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56054624/

相关文章:

ios - 归档时 : A struct gives "Redundant protocol error", 而不是运行时

ios - 以编程方式为每个 ios 屏幕设计在底部动态创建 CGPoint

swift - 使用 Mapkit 进行位置授权时不断抛出此错误 : (0x14) "Unable to insert COPY_SEND"

ios - 如何更新另一个 UIViewController 上的进度 View - SWIFT?

swift - GoogleSignIn 不适用于 YouTube API (Swift)

ios - 我如何获得 Alamofire get-request 的 location-header?

ios - 使用 Swift 切换 CoreLocation

swift - 将 Swift 字典转换为字符串

ios - NSKeyValueObservingOptions 快速错误

ios - Alamofire异步请求在for循环中乱序发生