当我调用API并锁定手机屏幕或最小化应用程序时,Alamofire给我一个错误。
”该操作无法完成。软件导致连接 中止”
请给我解决此问题的方法。
答案 0 :(得分:1)
这是 Alamofire 的 GitHub 页面上我认为有用的同一问题的答案:
<块引用>[...] 这是一个潜在的系统错误,当网络请求在后台处理过程中被终止时可能会发生。我建议您围绕网络请求实施后台任务,以使它们保持足够长的时间以在后台完成。您可以在 Apple's dev forums 上找到详尽的文档。一旦您正确处理了该转换,错误就会停止,或者让您有机会正确取消请求。[
答案 1 :(得分:0)
我认为当应用程序进入后台时,iOS 12在最后一个请求返回结果之前关闭了连接。您可以使用以下代码解决问题:
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {
[self sendBackgroundDataToServer];
}
- (void) sendBackgroundDataToServer {
UIBackgroundTaskIdentifier bgTask = UIBackgroundTaskInvalid;
bgTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
}];
NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:2];
[dictionary setObject:[NSNumber numberWithDouble:lc.coordinate.latitude] forKey:@"floLatitude"];
[dictionary setObject:[NSNumber numberWithDouble:lc.coordinate.longitude] forKey:@"floLongitude"];
// send to server with a synchronous request
// AFTER ALL THE UPDATES, close the task
if (bgTask != UIBackgroundTaskInvalid) {
[[UIApplication sharedApplication] endBackgroundTask:bgTask];
}
}
答案 2 :(得分:0)
答案 3 :(得分:0)
我找到了解决此问题的准确方法:
AppDelegate:
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
APIManager.shared.backgroundCompletionHandler = completionHandler
}
在您的API管理器类中:
private lazy var backgroundManager: Alamofire.SessionManager = {
let bundleIdentifier = "com.YourDomain.YourAppName"
return Alamofire.SessionManager(configuration: URLSessionConfiguration.background(withIdentifier: bundleIdentifier + ".background"))
}()
var backgroundCompletionHandler: (() -> Void)? {
get {
return backgroundManager.backgroundCompletionHandler
}
set {
backgroundManager.backgroundCompletionHandler = newValue
}
}
如何调用API:
let backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: nil)
backgroundManager.session.configuration.shouldUseExtendedBackgroundIdleMode = true
backgroundManager.startRequestsImmediately = true
backgroundManager.session.configuration.timeoutIntervalForRequest = 180
backgroundManager.request(url, method: apiType, parameters: dict, encoding: URLEncoding.default, headers: headers)
.responseJSON(queue: .main) { (response: DataResponse<Any>) in
UIApplication.shared.endBackgroundTask(backgroundTaskIdentifier)
switch(response.result) {
case .success(_):
case .failure(_):
}
}