logo
down
shadow

Swift: Why is my completionHandler closure returning a value?


Swift: Why is my completionHandler closure returning a value?

By : user2957136
Date : November 23 2020, 01:01 AM
it helps some times This or a close variation is how I do nearly all of my networking. It looks like your implementation isn't actually doing anything.
code :
func logIn() {
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true

    let url = NSURL(string: "https://www.photoshelter.com/psapi/v3/mem/authenticate?api_key=(api_key)&email=(email)&password=(password)&mode=token")
    let session = NSURLSession.sharedSession()

    // Request
    let request = NSMutableURLRequest(URL: url!)
    // You can set request properties like HTTPMethod and HTTPBody to customize things

    let loginUserDataTask = session.dataTaskWithRequest(request, completionHandler: { data, response, error in
        var success = false

        if let error = error {
            println("Failure! \(error)")
            if error.code == -999 { return }
        } else if let httpResponse = response as? NSHTTPURLResponse {
            if httpResponse.statusCode == 200 {
                if let array = parseJSON(data) {
                    success = true
                    // Do something with array
                }
            } else {
                println("Failure! \(response)")
            }
        }
        dispatch_async(dispatch_get_main_queue()) {
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        }
    })
    loginUserDataTask?.resume()
}
func parseJSON(data: NSData) -> [AnyObject]? {
    var error: NSError?
    if let json = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: &error) as? [AnyObject] {
        return json
    } else if let error = error {
        println("JSON Error: \(error)")
    } else {
        println("Unknown JSON Error")
    }
    return nil
}


Share : facebook icon twitter icon
Swift - CLGeocoder reverseGeocodeLocation completionHandler closure

Swift - CLGeocoder reverseGeocodeLocation completionHandler closure


By : Keith
Date : March 29 2020, 07:55 AM
I hope this helps . I found the answer I needed in this thread: Set address string with reverseGeocodeLocation: and return from method
The issue lies with the fact that reverseGeocodeLocation is asynchronous, the method is returning a value before the completionBlock sets p in my example.
code :
func showAddViewController(placemark:CLPlacemark){
    self.performSegueWithIdentifier("add", sender: placemark) 
}

func getPlacemarkFromLocation(location: CLLocation){
    CLGeocoder().reverseGeocodeLocation(location, completionHandler:
        {(placemarks, error) in
            if error {println("reverse geodcode fail: \(error.localizedDescription)")}
            let pm = placemarks as [CLPlacemark]
            if pm.count > 0 { self.showAddPinViewController(placemarks[0] as CLPlacemark) }
    })
}
How to use completionHandler Closure with return in Swift?

How to use completionHandler Closure with return in Swift?


By : user2064199
Date : March 29 2020, 07:55 AM
wish help you to fix your issue I am trying to us a RESTful API that returns some json data. I want to encapsulate the code that creates the HTTP Request and sets the headers in its own method so I can call it by entering a url String and then have the method return a JSON object.
code :
func getSomething(callback: (Array<AnyObject>) -> ()) {
    var dataTask = NSURLSessionDataTask()
    dataTask = session.dataTaskWithRequest(request) { (data, response, error) in
        if (error == nil) {
            var callbackArray = Array<MyObject>()
            let responseDict = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: nil) as NSDictionary
            let response = responseDict.objectForKey("response_key") as NSDictionary
            let array = response.objectForKey("array_key") as NSArray

            for item: AnyObject in array {
                var arrayItem = MyObject(dict: item as NSDictionary)
                callbackArray.append(arrayItem)
            }

            callback(callbackArray)
        } else {
            // handle an error
        }
    }
    dataTask.resume()
}
getSomething() { (response) in
    if let responseArray = response as? Array<MyObject> {
        self.somethings = responseArray
    }
}
Returning a value from a Swift function containing a closure

Returning a value from a Swift function containing a closure


By : Granulr
Date : March 29 2020, 07:55 AM
will help you Add a completion handler (named dataHandler in my example) to your loadData function:
code :
private func loadData(dataHandler: ([Item])->()) throws {
    var items = [Item]()
    let jsonUrl = "http://api.openweathermap.org/data/2.5/forecast/daily?units=metric&cnt=7&q=coventry,uk"
    print(jsonUrl)
    let session = NSURLSession.sharedSession()
    guard let shotsUrl = NSURL(string: jsonUrl) else {
        throw JSONError.InvalidURL(jsonUrl)
    }
    session.dataTaskWithURL(shotsUrl, completionHandler: {(data, response, error) -> Void in
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
            print(json)
            guard let days:[AnyObject] = (json["list"] as! [AnyObject]) else {
                throw JSONError.InvalidArray
            }
            for day in days {
                guard let timestamp:Double = day["dt"] as? Double else {
                    throw JSONError.InvalidKey("dt")
                }
                print(timestamp)
                let date = NSDate(timeIntervalSince1970: NSTimeInterval(timestamp))
                guard let weather:[AnyObject] = day["weather"] as? [AnyObject] else {
                    throw JSONError.InvalidArray
                }
                guard let desc:String = weather[0]["description"] as? String else {
                    throw JSONError.InvalidKey("description")
                }
                guard let icon:String = weather[0]["icon"] as? String else {
                    throw JSONError.InvalidKey("icon")
                }
                guard let url = NSURL(string: "http://openweathermap.org/img/w/\(icon).png") else {
                    throw JSONError.InvalidURL("http://openweathermap.org/img/w/\(icon).png")
                }
                guard let data = NSData(contentsOfURL: url) else {
                    throw JSONError.InvalidData
                }
                guard let image = UIImage(data: data) else {
                    throw JSONError.InvalidImage
                }
                guard let temp:AnyObject = day["temp"] else {
                    throw JSONError.InvalidKey("temp")
                }
                guard let max:Float = temp["max"] as? Float else {
                    throw JSONError.InvalidKey("max")
                }
                let newDay = Item(date: date, description: desc, maxTemp: max, icon: image)
                print(newDay)
                items.append(newDay)
            }
            dataHandler(items)
        } catch {
            print("Fetch failed: \((error as NSError).localizedDescription)")
        }
    }).resume()
}

do {
    try loadData { itemsArray in
        print(itemsArray)
    }
} catch {
    print(error)
}
CompletionHandler doesn't work with closure in UIAlertController

CompletionHandler doesn't work with closure in UIAlertController


By : Theresa X
Date : March 29 2020, 07:55 AM
it should still fix some issue You never actually call the completion handler you pass to alert. All you do is add it to an array.
There is no need for the completionHandlers array (at least not in the code you posted). And you do not need to dismiss the alert in the alert action.
code :
let ok: UIAlertAction = UIAlertAction.init(title: okButton, style: .default) { (_) in
    completionHandler()
}
CompletionHandler and Closure

CompletionHandler and Closure


By : Marcelo Mita
Date : March 29 2020, 07:55 AM
To fix the issue you can do Completion handler and closure are synonyms. They are called blocks in Objective-C.
You can think of them as objects that execute a bloc of code when they are called (much like a function).
code :
// My view controller has a property that is a closure
// It also has an instance method that calls the closure
class ViewController {

    // The closure takes a String as a parameter and returns nothing (Void)
    var myClosure: ((String) -> (Void))?
    let helloString = "hello"

    // When this method is triggered, it will call my closure
    func doStuff() {
        myClosure(helloString)?
    }
}

let vc = ViewController()

// Here we define what the closure will do when it gets called
// All it does is print the parameter we've given it
vc.myClosure = { helloString in
    print(helloString) // This will print "hello"
}

// We're calling the doStuff() instance method of our view controller
// This will trigger the print statement that we defined above
vc.doStuff()
shadow
Privacy Policy - Terms - Contact Us © ourworld-yourmove.org