首页 > 解决方案 > 在 URLSession.shared.dataTask 之后,它要么不返回错误,要么不成功

问题描述

URLSession.shared.dataTask它不是返回错误或成功之后。

完成处理程序没有被调用。我该如何检查或如何进一步进行。该应用程序正常运行没有错误,但显示的屏幕上没有数据。

func getPromotionsData() {
    ConnectionManager.sharedInstance()?.getPromotions(PROMOTIONS, withCompletion: {
        result, error in
        if let result = result {
            print("result: \(result)")
        }
        var arrPromotions: [Any] = []
        if let object = result?["promotions"] as? [Any] {
            arrPromotions = object
        }
        self.dataSource = []
        if let arrPromotions = arrPromotions as? [AnyHashable] {
            self.dataSource = arrPromotions
        }
        DispatchQueue.main.async(execute: {
            self.collectionView.reloadData()
        })
    })
}
func getPromotions(_ path: String?, withCompletion completion: @escaping (_ result: [AnyHashable : Any]?, _ error: Error?) -> Void) {
    let strPath = "/\(API)/\(path ?? "").json"
    let url = strPath.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed)
    makeRequest(BASE_URL, path: url, httpMethod: GET_METHOD, httpBody: nil, completion: completion)
}
func makeRequest(_ url: String?, path: String?, httpMethod: String?, httpBody httpBoday: Data?, completion: @escaping (_ result: [AnyHashable : Any]?, _ error: Error?) -> Void) {
    let headers = [
        "cache-control": "no-cache",
        "Authorization": "Token f491fbe3ec54034d51e141e28aaee87d47bb7e74"
    ]
    var request: URLRequest? = nil
    if let url = URL(string: "\(url ?? "")\(path ?? "")") {
        request = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
    }
    request?.httpMethod = httpMethod ?? ""
    request?.allHTTPHeaderFields = headers
    let configuration = URLSessionConfiguration.default
    configuration.httpCookieStorage = nil
    configuration.requestCachePolicy = NSURLRequest.CachePolicy.reloadIgnoringLocalAndRemoteCacheData
    if #available(iOS 11.0, *) {
        configuration.waitsForConnectivity = false
    }
    let session = URLSession(configuration: configuration)
    //        let session = URLSession.shared
    var task: URLSessionDataTask? = nil
    print ("Request =======>",request)
    if let req = request {
        task = session.dataTask(with: request! , completionHandler: {
            data, response, error in
            var result: Any? = nil
            if error != nil {
                if let error = error {
                    print("\(error)")
                }
                if completion != nil {
                    completion(nil, error)
                }
            } else
            {
                var string: String? = nil
                if let data = data {
                    string = String(data: data, encoding: .utf8)
                }
                string = self.string(byRemovingControlCharacters: string)

            do {
                if let data = string?.data(using: .utf8) {
                    result = try JSONSerialization.jsonObject(with: data, options: []) as!  [AnyHashable : Any]
                    print ("Result ===============>",result)
                }
            } catch {
            }
            if completion != nil {
                completion(result as! [AnyHashable : Any], error)
            }
        }
    })
}
task?.resume()
}

标签: iosswift

解决方案


实际上,完成块是一个异步过程,我正在等待该过程在调试模式下结束后立即返回控件。它现在按预期工作


推荐阅读