gpt4 book ai didi

swift - 闭包不更新局部变量

转载 作者:行者123 更新时间:2023-11-30 10:45:35 25 4
gpt4 key购买 nike

如何更新 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com