bwhite
bwhite

Reputation: 3

Calling a completionHandler when an error occurs

Im trying to pass a bool to my completion handler. When the app works, the result of passing the bool to my completion handler determines what alert I display. If I call it inside my error check, the app crashes/locks up. If I call it anywhere else, everything works as expected? I'm lost and can't find the answer to this one. Please help.

class func TestConnection(_ urlBase: String, usingCommand command: String, completionHandler: @escaping (Bool) -> Void) {
        let urlString = urlBase + "/" + command
        var IsValidConnection = false
        guard let url = URL(string: urlString) else {
            completionHandler(IsValidConnection)
            return
        }

        URLSession.shared.dataTask(with: url) { (data, response, error) in      
            //App blows up when running this block of code.
            //Doesn't return. App crashes/locks up
            guard error == nil else {
                completionHandler(false)
                return
            }
            //App works as expected when running code below
            guard let _: HTTPURLResponse = response as? HTTPURLResponse else {
                completionHandler(false)
                return
            }

            let serverResponse = response as! HTTPURLResponse

            if serverResponse.statusCode == 200 {
                IsValidConnection = true
            }

            completionHandler(IsValidConnection)

        }.resume()
    }

Upvotes: 0

Views: 55

Answers (1)

barbarity
barbarity

Reputation: 2488

The problem is URLSession.shared.dataTask has its own completionHandler named completionHandler. Just rename your handler to testConnectionCompletionHandler:

class func TestConnection(_ urlBase: String, usingCommand command: String, testConnectionCompletionHandler: @escaping (Bool) -> Void) {
    let urlString = urlBase + "/" + command
    var IsValidConnection = false
    guard let url = URL(string: urlString) else {
        testConnectionCompletionHandler(IsValidConnection)
        return
    }

    URLSession.shared.dataTask(with: url) { (data, response, error) in      
        //App blows up when running this block of code.
        //Doesn't return. App crashes/locks up
        guard error == nil else {
            testConnectionCompletionHandler(false)
            return
        }
        //App works as expected when running code below
        guard let _: HTTPURLResponse = response as? HTTPURLResponse else {
            testConnectionCompletionHandler(false)
            return
        }

        let serverResponse = response as! HTTPURLResponse

        if serverResponse.statusCode == 200 {
            IsValidConnection = true
        }

        testConnectionCompletionHandler(IsValidConnection)

    }.resume()
}

More info: https://developer.apple.com/documentation/foundation/urlsession/1407613-datatask

Upvotes: 1

Related Questions