gpt4 book ai didi

ios - 当应用程序在后台时,不会调用 AFHTTPSessionManager block

转载 作者:行者123 更新时间:2023-11-29 10:34:24 30 4
gpt4 key购买 nike

我的应用得到静默推送,然后使用 AFNetworking 在后台做一些 http 请求,但它没有进入完整的 block ,代码是:

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
[manager GET:urlString
parameters:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"response objece:%@", responseObject);
}
failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"error:%@", error);
}];

然后我发现也许我可以使用 NSURLSessionConfiguration 来配置 session :

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"com.company.backgroundDownloadSession"];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:configuration];
[manager GET:urlString
parameters:nil
success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(@"response objece:%@", responseObject);
}
failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"error:%@", error);
}];

但是 AFNetworking 崩溃说:“由于未捕获的异常‘NSGenericException’而终止应用程序,原因:‘后台 session 不支持数据任务。’”我应该怎么办?感谢您的帮助!

最佳答案

几个想法:

  1. 适当的背景 NSURLSessionConfiguration 需要 NSURLSessionDownloadTaskNSURLSessionUploadTask。不过,GET 方法会创建 NSURLSessionDataTask

    要使用下载或上传任务,您必须单独构建您的请求,然后利用 AFURLSessionManager发出下载或上传。尽管如此,如果您尝试创建 HTTP GET/POST 样式的请求,您可以使用各种请求序列化程序创建请求。只需使用 AFHTTPRequestSerializer 方法 requestWithMethod

    有关将 AFNetworking 与后台 NSURLSessionConfiguration 结合使用的基本介绍,请参阅 https://stackoverflow.com/a/21359684/1271826 .您必须将其与上面讨论的 requestWithMethod 结合起来。

    请注意,使用特定于任务的完成 block 时要小心(因为即使应用程序终止并且这些 block 早已不复存在,任务仍会继续)。正如后台下载任务的 AFNetworking 文档所说:

    Warning: If using a background NSURLSessionConfiguration on iOS, these blocks will be lost when the app is terminated. Background sessions may prefer to use setDownloadTaskDidFinishDownloadingBlock: to specify the URL for saving the downloaded file, rather than the destination block of this method.

  2. 如果您提出的请求不多,如果用户碰巧在请求仍在进行时离开了您的应用,则只要求操作系统稍等片刻可能会更容易。请参阅 App Programming Guide for iOS: Background Execution执行有限长度任务部分.

    最重要的是,在发出请求之前,请执行以下操作:

    UIApplication *application = [UIApplication sharedApplication];

    bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{
    // Clean up any unfinished task business by marking where you
    // stopped or ending the task outright.
    [application endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
    }];

    然后在请求的完成 block 中,你可以终止后台任务:

    if (bgTask != UIBackgroundTaskInvalid) {
    [application endBackgroundTask:bgTask];
    bgTask = UIBackgroundTaskInvalid;
    }

    这只适用于有限长度的任务,但它可能比尝试在后台 NSURLSessionConfiguration 更容易。

关于ios - 当应用程序在后台时,不会调用 AFHTTPSessionManager block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27852606/

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