greeneye12
greeneye12

Reputation: 73

Swift - How to get return value in a variable as a result of an asynchronous request

I am new to SWIFT and app development, and I am trying to get my head around closures.

I am using Alamofire and SwiftyJSON. I have read a lot of posts about it but I still don't get how to get to the end of the problem.

I have first the block of code with the completion handler closure

func SendGeocodeRequest(query:String, completionHandler: @escaping (Float)-> Void) {

    var ltd:Float = 1.0
    AF.request(query).responseJSON { response in

        switch response.result {
        case .success(let value):
            let json=JSON(value)

            ltd  = json["results"][0]["geometry"]["location"]["lat"].floatValue
            completionHandler(ltd)
            
        case .failure(let error):
            print(error)
        }
    }
}

Then I am calling the function :

SendGeocodeRequest(query: query_origin) { ltd in
    print("ltd value is \(ltd)")
    
}

and I get the latitude from the google API I am calling in a print statement.

My issue is the following : Instead of the print statement, how can I store this value in a variable and use it outside the function ? As the function has a void return type, I cannot see how to do this. I would like to be able to assign the latitude value that lives inside my SendGeocodeRequest function to a variable so I can use later in my code [Edited for more clarity]

Upvotes: 1

Views: 1503

Answers (1)

Pawan
Pawan

Reputation: 90

Lets say you are calling this function in a View Controller called ViewController.swift. Just create a class property in the View Controller called latitude and assign the response from the API call to this property.

//ViewController.swift
class ViewController: UIViewController {
    var latitude : Float = 0.0
    
    SendGeocodeRequest(query: query_origin) { ltd in
        self.latitude = ltd
    }
}

Then use the latitude property wherever you want.

Upvotes: 1

Related Questions