简体   繁体   English

在 URLSession.shared.dataTask 之后要么不返回错误要么成功

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

After URLSession.shared.dataTask it's not either returning error or success.URLSession.shared.dataTask之后,它既不返回错误也不返回成功。

The completion handler is not getting called.未调用完成处理程序。 How can I check or how can I proceed further.我如何检查或如何进一步进行。 There is no error the app is working as such, but without data on the screen which is displayed.应用程序正常工作没有错误,但显示的屏幕上没有数据。

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

Actually the completion block is an asynchronous process and i was waiting for the control to go back immediately after the process ends in debugging mode.实际上完成块是一个异步过程,我正在等待控制在调试模式结束后立即返回。 It works now as expected它现在按预期工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在URLSession.shared.dataTask之后调用performSegue - Call performSegue after URLSession.shared.dataTask URLSession.shared.dataTask 冻结 UI - URLSession.shared.dataTask freezes the UI 在URLSession.shared.dataTask中执行performSegueWithIdentifier(with:url) - performSegueWithIdentifier while in URLSession.shared.dataTask(with: url) 为什么没有在第二个 URLSession.shared.dataTask 之后/内执行代码,即在初始 URLSession.shared.dataTask 的 do 块内? 迅速 - Why isn't code being executed after/within a second URLSession.shared.dataTask, that is within an initial URLSession.shared.dataTask’s do block? Swift 如何获取请求中标头的值(URLSession.shared.dataTask(with:request){(数据,响应,错误) - How get value of headers in request (URLSession.shared.dataTask(with: request) { (data, response, error) 当应用程序处于后台时调用URLSession.shared.dataTask - Invoke URLSession.shared.dataTask when the app is background 在URLSession.shared.dataTask期间从异步关闭存储数据 - Storing data from an asynchronous closure during URLSession.shared.dataTask URLSession.shared.dataTask的完成处理程序内部的闭包 - closure inside completion handler of URLSession.shared.dataTask 使用URLSession.shared.dataTask中的JSON和字典进行Swift 3编译器错误 - Swift 3 Compiler Errors with JSON and Dictionaries within URLSession.shared.dataTask 使用 URLSession.shared.dataTask 发出 api 请求 - Making an api request using URLSession.shared.dataTask
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM