簡體   English   中英

在 URLSession.shared.dataTask 之后要么不返回錯誤要么成功

[英]After URLSession.shared.dataTask its either not returning error or success

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()
}

實際上完成塊是一個異步過程,我正在等待控制在調試模式結束后立即返回。 它現在按預期工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM