0

I'm new to swift and iOS development in general, so excuse me if this question is silly, but I can't seem to get my function to return the result from an API GET request. I am running a Microsoft SQL server on my friend's computer and I am remotely accessing it with DreamFactory. DreamFactory is creating and managing the API for the SQL queries. I am hosting the DreamFactory API web server on my localhost and I am accessing it through my iOS app.

This is what I have so far.

func validId() -> Bool {
    var queryId: Int = 0 // just for testing

    let table = "SM.Customers"
    // this url looks like ( http://localhost:8080/api/v2/db/_table/SM.Customers/1989/?api_key=065dce537)
    let url = URL(string: "\(urlString)\(table)/\(self.id)?api_key=\(self.api_key)")!

    URLSession.shared.dataTask(with: url, completionHandler: {
        (data, response, error) in
        if(error != nil){
            print(error.debugDescription)
        }else{
            do{
                self.userData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! [String: AnyObject]
                OperationQueue.main.addOperation {
                    queryId = self.userData["CustId"] as! Int
                    print(queryId)
                }

            }catch let error as NSError{
                print(error)
            }
        }



    }).resume()


    return (String(queryId) == self.id)

}

I can do things under OperationQueue.main.addOperation {...} with the data that I pull from the db, but I can't really return a value or assign the value to a variable outside of the task code block. This function will print(queryId) as 1989 but it will return false because it's reading (String(queryId) == self.id) as (0 == 1989).

Any ideas how I can resolve this?

lokilindo
  • 682
  • 5
  • 17
  • Return statement is execute before the completion block of `dataTask`, so you need to use completion handler with your function `validId` check this one http://stackoverflow.com/questions/42241177/how-to-call-a-func-within-a-closure to make completion handler – Nirav D Apr 17 '17 at 03:53
  • Thank for the comment. But how do I return a `bool` in the `validId` function? That example doesn't explain. I can already update the UI elements within `OperationQueue.main.addOperation {...}`, what I want is to return a value. – lokilindo Apr 17 '17 at 13:56
  • You cannot return any value from this validId function because it is making an async call, What you need is to create completion block with your function `validId` just like that suggested solution. – Nirav D Apr 18 '17 at 04:40

0 Answers0