Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift 3, URLSession dataTask completionHandler not called

I am writing a library, So not using UIKit, Even in my iOS app same code works, but when i execute in command line in doesn't . In PlayGround also it seems working.

For some reason callback is not getting triggered, so print statements are not executing.

internal class func post(request: URLRequest, responseCallback: @escaping (Bool, AnyObject?) -> ()) {
    execTask(request: request, taskCallback: { (status, resp)  -> Void in
            responseCallback(status, resp)
    })
}

internal class func clientURLRequest(url: URL, path: String, method: RequestMethod.RawValue,  params: Dictionary<String, Any>? = nil) -> URLRequest {
    var request = URLRequest(url: url)
    request.httpMethod = method
    do {
        let jsonData = try JSONSerialization.data(withJSONObject: (params! as [String : Any]), options: .prettyPrinted)

        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.httpBody = jsonData
    } catch let error as NSError {
        print(error)
    }
    return request
}

private class func execTask(request: URLRequest, taskCallback: @escaping (Bool,
    AnyObject?) -> ()) {

    let session = URLSession(configuration: URLSessionConfiguration.default)
    print("THIS LINE IS PRINTED")
    let task = session.dataTask(with: request, completionHandler: {(data, response, error) -> Void in
        if let data = data {
            print("THIS ONE IS NOT PRINTED")
            let json = try? JSONSerialization.jsonObject(with: data, options: [])
            if let response = response as? HTTPURLResponse , 200...299 ~= response.statusCode {
                taskCallback(true, json as AnyObject?)
            } else {
                taskCallback(false, json as AnyObject?)
            }
        }
    })
    task.resume()
}

Edits -: I am writing a library, So not using UIKit, Even in my iOS app same code works, but when i execute in command line in doesn't . In PlayGround also it seems working.

like image 990
xrage Avatar asked Aug 20 '16 11:08

xrage


People also ask

How do you use completion handler in Swift?

Here’s an example of a function that takes a completion handler: It takes two arguments: request: URLRequest and completionHandler: @escaping (Data?, URLResponse?, Error?) -> Swift.Void. The second argument is a closure that takes (Data?, URLResponse?, Error?) as arguments and returns nothing ( Swift.Void ).

What are the common urlsession errors in Swift 3?

URLSession dataTask timeout error 1 Ios Swift3 : URLSession shared datatask showing an error 4 ambiguous use of selector dataTask(with: completionHandler:)

How do I send and receive data with urlsessiondatatask?

Data tasks: send and receive data with URLSessionDataTask, by using NSData objects. They’re the most common for webservice requests, for example when working with JSON. Upload tasks: send files to a webserver with URLSessionUploadTask.

What is urlsessionuploadtask in AWS?

They’re the most common for webservice requests, for example when working with JSON. Upload tasks: send files to a webserver with URLSessionUploadTask. They’re similar to data tasks, but URLSessionUploadTask instances can also upload data in the background (or when an app is suspended).


1 Answers

I made a simple App from scratch. (Xcode 8 beta 6 / swift 3) In controller I pasted Your code. (plus url creation..) I see all in debugger:

THIS ONE IS PRINTED

THIS ONE IS PRINTED, TOO

I AM BACK

so it seems workin.

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let URLString = "https://apple.com"
        let url = URL(string: URLString)
        let request = URLRequest(url: url!)


        ViewController.execTask(request: request) { (ok, obj) in

            print("I AM BACK")

        }

    }

    private class func execTask(request: URLRequest, taskCallback: @escaping (Bool,
        AnyObject?) -> ()) {

        let session = URLSession(configuration: URLSessionConfiguration.default)
        print("THIS LINE IS PRINTED")
        let task = session.dataTask(with: request, completionHandler: {(data, response, error) -> Void in
            if let data = data {
                print("THIS ONE IS PRINTED, TOO")
                let json = try? JSONSerialization.jsonObject(with: data, options: [])
                if let response = response as? HTTPURLResponse , 200...299 ~= response.statusCode {
                    taskCallback(true, json as AnyObject?)
                } else {
                    taskCallback(false, json as AnyObject?)
                }
            }
        })
        task.resume()
    }

}
like image 86
ingconti Avatar answered Nov 16 '22 23:11

ingconti