當應用程式進入后臺時,它想要發出一個請求,不幸的是它收到錯誤:
sessionTaskFailed (error: Error Domain = NSURLErrorDomain Code = -1005 "The network connection was lost...")
代碼:
override func viewDidLoad() {
super.viewDidLoad()
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
}
@objc func appMovedToBackground() {
let URL: String = "http://www.test.com/"
AF.request(URL, method: .post, parameters: parameters, headers: headers)
.responseJSON { [] response in
switch response.result {
case .success(let data):
print(data)
case .failure(let error):
print(error)
}
}
}
uj5u.com熱心網友回復:
看起來您應該實作后臺任務。蘋果檔案給出了一個如何做的例子:
func sendDataToServer( data : NSData ) {
// Perform the task on a background queue.
DispatchQueue.global().async {
// Request the task assertion and save the ID.
self.backgroundTaskID = UIApplication.shared.
beginBackgroundTask (withName: "Finish Network Tasks") {
// End the task if time expires.
UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)
self.backgroundTaskID = UIBackgroundTaskInvalid
}
// Send the data synchronously.
self.sendAppDataToServer( data: data)
// End the task assertion.
UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)
self.backgroundTaskID = UIBackgroundTaskInvalid
}
}
編輯
我沒有編譯這段代碼,但根據 Apple檔案,它可以這樣做:
final class ViewControler: UIViewController {
private var backgroundTaskID: UIBackgroundTaskIdentifier?
override func viewDidLoad() {
super.viewDidLoad()
if #available(iOS 13.0, *) {
NotificationCenter.default.addObserver(self,
selector: #selector(willResignActive),
name: UIScene.willDeactivateNotification,
object: nil)
} else {
NotificationCenter.default.addObserver(self,
selector: #selector(willResignActive),
name: UIApplication.willResignActiveNotification,
object: nil)
}
}
@objc func willResignActive(_ notification: Notification) {
// Perform the task on a background queue.
DispatchQueue.global().async {
// Request the task assertion and save the ID.
self.backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Finish Network Tasks") {
// End the task if time expires.
UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)
self.backgroundTaskID = .invalid
}
self.sendRequest()
}
}
func sendRequest() {
let URL: String = "http://www.test.com/"
AF.request(URL, method: .post, parameters: parameters, headers: headers)
.responseJSON { [unowned self] response in
// End the task assertion.
UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)
self.backgroundTaskID = .invalid
switch response.result {
case .success(let data):
print(data)
case .failure(let error):
print(error)
}
}
}
}
在這段代碼中,我們訂閱時,應用程式的通知,將 進入到后臺,并創建一個后臺任務。在后臺任務中,我們執行必要的請求。如果這個請求在回應閉包中的執行速度超過 5 秒,我們就會使我們的后臺任務無效并完成它的作業。如果請求執行時間超過 5 秒,則后臺任務終止。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/329705.html
上一篇:歸檔前檢查是否有任何提交要做?
