swift - 闭包不更新局部变量

标签 swift closures alamofire

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

我正在尝试更新使用 Alamofire 请求成功发送的消息数的计数。执行此操作的明显位置是在闭包内部 - 在 .success 案例中。

所以我试图更新闭包内的局部变量,但其范围仅限于闭包内部。当我进入关闭状态时,我看到本地更新。但是当我在闭包下方检查它时,它的值为 0。因此 print() 显示“已发送 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
}

最佳答案

您需要使用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: ")

}

关于swift - 闭包不更新局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55814959/

相关文章:

json - 由于对成员 jsonObject 的引用不明确,我无法编译我的 alamofire 代码。为什么?

ios - 如何在 Alamofire 主体 + 参数中创建请求

swift - 使用 Swift 选择 NSTextField 中的所有文本

swift - 在 AVPlayer 中禁用时间搜索

swift - Swift 中等效的 C 数组

javascript - 为什么我无法切换 for 语句中每个元素(组内)的可见性,而只能切换组中的最后一个元素?

swift - 如何在stackview文本字段中获取数字以快速获取otp的动态数字键盘

javascript - 有什么理由故意引入闭包来防止变量提升?

javascript - 将方法分配给原型(prototype)不起作用

ios - 从另一个应用程序返回后,Alamofire(URL)请求失败,例如 : Facebook