I am trying to create a Warehouse management app for iOS using Swift and the Google Sheets API. I am creating a query to get the data stored in a sheet and save the data in an array of WarehouseItem objects. The code I have created is the following:
class GoogleHandler{
private let scopes = [kGTLRAuthScopeSheetsSpreadsheets,kGTLRAuthScopeSheetsDrive]
private let service = GTLRSheetsService()
private let API_key = "AIzaSyCw8OzrgB6YhWIiQi7fpzTDZ_dgxUQl-os"
private var warehouseItems: [WarehouseItem] = []
func readData(){
if GIDSignIn.sharedInstance().currentUser != nil{
GIDSignIn.sharedInstance().clientID.append("215857501935-iiqidhd8sp72419m2rqq53ntl1cvl7df.apps.googleusercontent.com")
GIDSignIn.sharedInstance().scopes = scopes
self.service.authorizer=GIDSignIn.sharedInstance().currentUser?.authentication.fetcherAuthorizer()
self.service.apiKey = API_key
let spreadsheet_id = "1xsD6KH8X49WMm_3FrFEuv12KEF5PCkmx-WdIF7Yl6R8"
let range = "A2:Z"
let query = GTLRSheetsQuery_SpreadsheetsValuesGet.query(withSpreadsheetId: spreadsheet_id, range: range)
service.executeQuery(query){ (ticket:GTLRServiceTicket, result:Any?, error:Error?) in
if let error = error{
print("Error",error.localizedDescription)
}else{
let data = result as? GTLRSheets_ValueRange
let rows = data?.values as? [[String]] ?? [[""]]
for row in rows{
let id : String = UUID().uuidString
let productCode: String = row[0]
let subcontractor: String = row[1]
let q : String = row[2]
let quantity : Int = Int(q)!
let lotNumber : String = row[3]
let expiryDate : String = row[4]
let productionDate : String = row[5]
let status : String = row[6]
let warehouseItem = WarehouseItem(id: id, productCode: productCode, sub_contractor: subcontractor, lotNumber: lotNumber, quantity: quantity, productionDate: productionDate, expiryDate: expiryDate)
warehouseItem.setStatus(status: status)
self.warehouseItems.append(warehouseItem)
}
}
}
}else{
}
}
func setWarehouseItems(warehouseItems: [WarehouseItem]){
self.warehouseItems = warehouseItems
}
}
class Warehouse{
private var warehouse_items : [WarehouseItem]
private let handler : GoogleHandler
init(){
self.handler = GoogleHandler()
self.warehouse_items = []
}
func readCurrentWarehouse(){
self.handler.setWarehouseItems(warehouseItems: self.warehouse_items)
handler.readData()
print(self.warehouse_items.count)
}
Everything in the code works perfectly, I gain access to my Google Spreadsheet without any problems. The problem with this code is that it seems that the query returns before the result is filled and the function readData() returns. As a result, when I am trying to print the number of warehouse items in the array warehouse_items within the function readCurrentWarehouse() of the Warehouse class, it prints 0. Is there any way to freeze the execution of the readData() function until the result is obtained?