Pablo prez
Pablo prez

Reputation: 199

iOS swift how can I await an async task inside a function that needs a return value

I am using swift 3.0 and have created a function that returns an Array of Integers. The arrays of Integers are very specific and they are gotten from a database therefore the HTTP call is asynchronous . This is a function because I use it in 3 different controllers so it makes sense to write it once . My problem is that the Async code is returned after the return statement at the bottom therefore it is returning nil . I have tried the example here Waiting until the task finishes however it is not working mainly because I need to return the value . This is my code

func ColorSwitch(label: [UILabel]) -> [Int] {

    for (index, _) in label.enumerated() {
       label[index].isHidden = true
    }

    // I need the value of this variable in the return
    // statement after the async is done
    var placeArea_id = [Int]()

    let urll:URL = URL(string:ConnectionString+"url")!

    let sessionn = URLSession.shared
    var requestt = URLRequest(url: urll)
    requestt.httpMethod = "POST"


    let group = DispatchGroup()
    group.enter()

    let parameterr = "http parameters"
    requestt.httpBody = parameterr.data(using: String.Encoding.utf8)
    let task =   sessionn.dataTask(with:requestt, completionHandler: {(data, response, error) in
        if error != nil {
            print("check check error")
        } else {
            do {

                let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
                DispatchQueue.main.async {

                    if let Profiles = parsedData?["Results"] as? [AnyObject] {
                        if placeArea_id.count >= 0 {
                            placeArea_id = [Int]()   
                        }

                        for Profiles in Profiles {

                            if let pictureS = Profiles["id"] as? Int {
                                placeArea_id.append(pictureS)
                            }
                        }
                    }
                    group.leave()
                }

            } catch let error as NSError {
                print(error)

            }
        }
    })
    task.resume()


    group.notify(queue: .main) {
   // This is getting the value however can't return it here since it 
   // expects type Void
    print(placeArea_id)

    }
   // this is nil
    return placeArea_id

}

I already checked and the values are returning inside the async code now just need to return it any suggestions would be great .

Upvotes: 0

Views: 4717

Answers (2)

Asleepace
Asleepace

Reputation: 3745

You will want to use closures for this, or change your function to be synchronous.

func ColorSwitch(label: [UILabel], completion:@escaping ([Int])->Void) {
    completion([1,2,3,4]) // when you want to return
}

ColorSwitch(label: [UILabel()]) { (output) in
    // output is the array of ints
    print("output: \(output)")
}

Here's a pretty good blog about closures http://goshdarnclosuresyntax.com/

Upvotes: 6

Michael Hulet
Michael Hulet

Reputation: 3499

You can't really have your function return a value from an asynchronous operation within that function. That would defeat the purpose of asynchronicity. In order to pass that data back outside of your ColorSwitch(label:) function, you'll need to also have it accept a closure that will be called on completion, which accepts an [Int] as a parameter. Your method declaration will need to look something like this:

func ColorSwitch(label: [UILabel], completion: @escaping ([Int]) -> Void) -> Void {

    for (index, _) in label.enumerated() {
        label[index].isHidden = true
    }

    var placeArea_id = [Int]()

    let urll:URL = URL(string:ConnectionString+"url")!

    let sessionn = URLSession.shared
    var requestt = URLRequest(url: urll)
    requestt.httpMethod = "POST"


    let group = DispatchGroup()
    group.enter()

    let parameterr = "http parameters"
    requestt.httpBody = parameterr.data(using: String.Encoding.utf8)
    let task =   sessionn.dataTask(with:requestt, completionHandler: {(data, response, error) in
        if error != nil {
            print("check check error")
        } else {
            do {

                let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
                DispatchQueue.main.async {

                    if let Profiles = parsedData?["Results"] as? [AnyObject] {
                        if placeArea_id.count >= 0 {
                            placeArea_id = [Int]()
                        }

                        for Profiles in Profiles {

                            if let pictureS = Profiles["id"] as? Int {
                                placeArea_id.append(pictureS)
                            }

                        }
                    }
                    group.leave()
                    completion(placeArea_id) // This is effectively your "return"
                }

            } catch let error as NSError {
                print(error)

            }

        }

    })
    task.resume()
}

Later on, you can call it like this:

ColorSwitch(label: []) { (ids: [Int]) in
    print(ids)
}

Upvotes: 4

Related Questions