【问题标题】:Closures not updating local variables闭包不更新局部变量
【发布时间】:2019-04-23 15:46:20
【问题描述】:

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

我正在尝试更新使用 Alamofire 请求成功发送的消息数的计数。这样做的明显地方是在闭包内 - 在 .success 案例中。

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

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

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
}

【问题讨论】:

  • “我错过了什么” 你错过了“异步”的含义。这意味着您正在打印之前您已经设置了numRecsSent!我写了一篇博文来帮助你:programmingios.net/what-asynchronous-means
  • @matt 感谢您的链接。我现在对它有了更好的处理。我编辑了我的问题以包含工作代码。我确信仍然存在问题,但它比我原来的帖子更接近。如果您将评论作为答案发布,我会接受。

标签: swift closures alamofire


【解决方案1】:

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

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-17
    • 2011-01-21
    • 2018-12-24
    • 1970-01-01
    • 2016-09-02
    • 1970-01-01
    • 2014-01-13
    • 1970-01-01
    相关资源
    最近更新 更多