闭包不更新局部变量

问题描述 投票:0回答:1

如何在Alamofire闭包内更新局部变量?

我正在尝试更新使用Alamofire请求成功发送的消息数#。显而易见的地方是封闭内部 - 在.success案例中。

所以我试图更新闭包内的局部变量,但它的范围仅限于闭包内部。当我进入关闭时,我看到本地更新。但是当我在闭包下面检查它时,它的值为0.因此print()显示'n RECORDS的SENT 0'。我怀疑这是因为它在调用闭包之前通过循环。

问题:1)我错过了什么? 2)我不理解completion()调用。我在代码中找不到该方法。它是我用回调替换的占位符吗?

func uploadSavedPacketsToServer(completion: @escaping (Int, Int) -> Void) {

var totalNumRecsToSend = recordsToSend.count
for (i, currentRec) in recordsToSend.enumerated() {

   // build request....

    Alamofire.request(request)
             .validate()
             .responseJSON { response in

             switch response.result {

             case .success:
                  // pass the # of recs remaining as well as total # of recs to send
                   completion( (totalNumRecsToSend - i),totalNumRecsToSend)

             case .failure(let error):
                   print("SUBMIT failure: \(error)")

                  // -1, 0 indicates a unique error. Parsed in completion handler
                   completion(-1, 0)   
             }
     }   // end closure
   }   // end for all records to send
}


// Executed AFTER the network call has returned!!
let completionHandler: (Int, Int) -> Void = { (numSent, numTotal) in

error checking ....
    if (numTotal - numSent == 0) {
        // SUCCESS
        // keep a running count of # packets sent to server in this period
        ServerConstants.numPktsUploaded += numSent
    }

    // Build the Notification
    // 1) Create the body content
    let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey: "Data Upload", arguments: nil)
    content.body = NSString.localizedUserNotificationString(forKey: strMsg, arguments: nil)

     // 2) Configure the trigger to appear 10 minutes from now. NOTE: using Calendar will accomodate for DST, TZs etc.
     var calendar = Calendar.current
     let trigger = UNCalendarNotificationTrigger(dateMatching: calendar.dateComponents([.year, .month, .day, .hour, .minute, .second, .timeZone],
                     from: Date(timeIntervalSinceNow: 1)), repeats: false)

     // 3) Create the Local Notification object
     let notify = UNNotificationRequest(identifier: "DataUpload", content: content, trigger: trigger)

     // 4) and queue it up
     UNUserNotificationCenter.current().add(notify, withCompletionHandler: nil)

     // reset our pkt counter
     ServerConstants.numPktsUploaded = 0             

     // and the time of our last upload
     ServerConstants.lastNotifyTime = currentTime    
     return
}

swift closures alamofire
1个回答
0
投票

所有异步请求完成后,您需要使用DispatchGroup进行通知

let g = DispatchGroup() /// <<<<< 1

for (i, currentRec) in recordsToSend.enumerated() {

    // build request....

    g.enter()  /// <<<<< 2

    Alamofire.request(request)
        .validate()
        .responseJSON { response in

            switch response.result {

            case .success:
                // pass the server's response back in 1st param, & error status in 2nd param
                completion(response.value, nil)

                // keep count of how many records were successfully sent
                self.setNumRecsSent()

            case .failure(let error):
                print("SUBMIT failure: \(error)")
                completion(nil, response.error)

            }

            g.leave()  /// <<<<< 3

    }   // end closure
}   // end for all records to send


g.notify(queue: .main) {  /// <<<<< 4

    print("SENT \(self.getNumRecsSent()) of \(numRecsToSend) RECORDS: ")

}
© www.soinside.com 2019 - 2024. All rights reserved.