Always returning blank but print out the result

off-topic

(Chester) #1

Just discovered this forum and super excited to contribute and learn.
Wondering if someone can help me solve this problem.
I wrote this class so when an object is created, it can go and fetch an stringID from another system (Square) and store the id in itself for later use.
I actually can have the print(returnValue) but the actual return is always "" (which is what I init with)
I tried to put my return statement immediately after they found the string, but it won't let me.
Ideas? (Code is below)

//
//  Location.swift
//  tipCal
//
//  Created by Chester Wong on 2018-09-03.
//  Copyright © 2018 Chester Wong. All rights reserved.
//

import Foundation
import Firebase
import SwiftyJSON
import Alamofire

class Location  {

var name : String = ""
var id : Int = 0
var long : Float = 0.0
var lat : Float = 0.0
var cashTip = 0.0
var posTip = 0.0
var totalWorkHours = 0.0
var averageTipPerHour =  0.0
var isSelected = false
var squareID = ""


func getSquareID(name: String) -> String {

    let header = ["Authorization": "Bearer xxxxxxxxxx"]
    var returnValue = ""
    
    Alamofire.request("https://connect.squareup.com/v2/locations", method: HTTPMethod.get, encoding: URLEncoding.default, headers: header).responseJSON(options: .allowFragments) { (reponse) in
        
        let json = JSON(reponse.data)
        
        for (key,subJson):(String, JSON) in json["locations"] {
            
            if name == subJson["name"].stringValue {
                
                returnValue = subJson["id"].stringValue
                print (returnValue)
                }
            
            }
    
        }
    return returnValue
    }

}

(Letanyan Arumugam) #2

By the time you return returnValue you most likely haven't set returnValue yet because the closure is run asynchronously. I would suggest passing in a completion handler instead of returning a value.

func getSquareID(name: String, completion: @escaping (String) -> Void) {
    let header = ["Authorization": "Bearer xxxxxxxxxx"]
    var returnValue = ""
    
    Alamofire.request("https://connect.squareup.com/v2/locations", method: HTTPMethod.get, encoding: URLEncoding.default, headers: header).responseJSON(options: .allowFragments) { (reponse) in
        
        let json = JSON(reponse.data)
        
        for (key,subJson):(String, JSON) in json["locations"] {
            
            if name == subJson["name"].stringValue {
                
                returnValue = subJson["id"].stringValue
                completion(returnValue)
                print (returnValue)
            
            }
    
        }
    }
}

Here's an article with more options. I haven't actually fully read it, but it looks promising.