ios – Wrong Print Order With Web Request

0
21

[ad_1]

I am trying to read data from Google Sheet API and get the last 5 rows. Here is my function:

func fetchData() {
    let range = "TestSheet"
    var convertedLogList : [Log] = []
    var fetchResult: [[String]] = []

    let query = GTLRSheetsQuery_SpreadsheetsValuesGet.query(withSpreadsheetId: Globals.shared.YOUR_SHEET_ID, range: range)
    
    Globals.shared.sheetService.executeQuery(query) { (ticket, result, error) in
        if let error = error {
            print(error)
            return
        }

        guard let values = (result as? GTLRSheets_ValueRange)?.values else {
            print("No data found.")
            return
        }
        
        fetchResult = values.map { $0.map { $0 as? String ?? "" } }
        
        for row in fetchResult {
            // convert [String] to a Log object
            var log = Log()
            log.timestamp = row[0]
            log.nthTime = row[1]
            log.openNew = row[2]
            if row.count == 4 {
                log.note = row[3]
            }
            convertedLogList.append(log)
        }
        print("===== convertedLogList: ", convertedLogList)
    }
    
    var latestLogs : [Log] = []
    var counter = 0
    // take the latest 5 logs
    for log in convertedLogList.reversed() {
        if counter < convertedLogList.count && counter < 5 {
            counter += 1
            latestLogs.append(log)
        } else {
            break
        }
    }
    print("+++++ latestLogs: ", latestLogs)
}

I have 2 print statements in my code but the print order is wrong. Here is the print output:

+++++ latestLogs: []
===== convertedLogList: [Log(id: xxxxxxxxx, timestamp: “10/24/2022”, nthTime: “1”, openNew: “Yes”, note: “), Log(id:xxxxxxx,….) …. ]

I wonder why the print order is wrong. How can I utilize the await with Google Sheet API in Swift to solve this issue?

[ad_2]