如何最好地构建代码以使用iOS中的AFNetworking和CoreData下载资源

如何最好地构建代码以使用iOS中的AFNetworking和CoreData下载资源,第1张

概述我首先使用AFHTTPClient下载单个索引文档,并使用CoreData记录每个记录.然后我需要启动一个单独的进程来下载每个单独的记录.最好的方法是什么? 为每个资源提出请求并让它们完成是否合理?可能有一百左右. 或者,我可以加载第一个,提交请求,然后加载成功并提交后续请求. 我正在使用CoreData更新数据库,我认为这意味着我需要为每个请求分别拥有一个NSManagedObjectConte 我首先使用AFhttpClIEnt下载单个索引文档,并使用CoreData记录每个记录.然后我需要启动一个单独的进程来下载每个单独的记录.最好的方法是什么?

为每个资源提出请求并让它们完成是否合理?可能有一百左右.

或者,我可以加载第一个,提交请求,然后加载成功并提交后续请求.

我正在使用CoreData更新数据库,我认为这意味着我需要为每个请求分别拥有一个NSManagedobjectContent?

我也很想知道,AFhttpClIEnt是在主线程上执行回调,还是在发起请求的线程上执行回调?我宁愿没有阻止主线程执行CoreData I / O.

解决方法 关于下载资源,您可以使用AFNetworking对它们进行排队.

您可以使用 – (voID)enqueuehttpRequestoperation:(AFhttpRequestoperation *)AFhttpClIEnt的 *** 作.

首先创建一个单例来保存自己的AFhttpClIEnt,如下所示:

@interface CustomhttpClIEnt : NSObject+ (AFhttpClIEnt *)sharedhttpClIEnt;@end@implementation CustomhttpClIEnt+(AFhttpClIEnt *)sharedhttpClIEnt {  static AFhttpClIEnt *sharedhttpClIEnt = nil;  if(sharedhttpClIEnt == nil) {    static dispatch_once_t oncetoken;    dispatch_once(&oncetoken,^{    // Create the http clIEnt    sharedhttpClIEnt = [AFhttpClIEnt clIEntWithBaseURL:[NSURL URLWithString:@"http://mybaseurl.com"]];    });  }  return sharedhttpClIEnt;}@end

然后排队你的请求,如下:

// Store the operations in case the failure block needs to cancel them__block NSMutableArray *operations = [NSMutableArray array];// Add operations for urlfor (NSURL *url in urls) {  NSURLRequest *request = [NSURLRequest requestWithURL:url];  __block AFhttpRequestoperation *operation = [[CustomhttpClIEnt sharedhttpClIEnt]                                            httpRequestoperationWithRequest:request                                            success:^( AFhttpRequestoperation *operation,ID responSEObject ){                                             // Do something                                           }                                            failure:^( AFhttpRequestoperation *operation,NSError *error ){                                             // Cancel all operations if you need to                                             for (AFhttpRequestoperation* operation in operations) {                                               [operation cancel];                                             }                                           }];  [operations addobject:operation];    }for (AFhttpRequestoperation* operation in operations) {  [[CustomhttpClIEnt sharedhttpClIEnt] enqueuehttpRequestoperation:operation];}

还有enqueueBatchOfhttpRequestoperations:progressBlock:completionBlock:如果需要监视进度.

AFNetworking项目:
https://github.com/AFNetworking/AFNetworking/

AFNetworking文档:
http://afnetworking.org/Documentation/index.html

总结

以上是内存溢出为你收集整理的如何最好地构建代码以使用iOS中的AFNetworking和CoreData下载资源全部内容,希望文章能够帮你解决如何最好地构建代码以使用iOS中的AFNetworking和CoreData下载资源所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1034679.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-24
下一篇2022-05-24

发表评论

登录后才能评论

评论列表(0条)

    保存