闭包不更新局部变量

时间:2019-04-23 15:46:20

标签: swift closures alamofire

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

我正在尝试更新使用Alamofire请求成功发送的msg计数。显然,这样做是在闭包内部-在.success情况下。

因此,我尝试在闭包内更新局部变量,但其范围仅限于闭包内。当我进入关闭时,我看到了本地更新。但是,当我在闭包下面对其进行检查时,其值为0。因此print()显示“已发送0个n RECORDS”。我怀疑是因为它在调用闭包之前就通过了循环。

问题: 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
}

1 个答案:

答案 0 :(得分: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: ")

}