How to better structure your code to load resources using AFNetworking and CoreData in iOS

First, I load one index document using AFHTTPClient and write each record using CoreData. Then I need to deploy a separate process to load each individual record. What is the best way to do this?

Is it possible to make a request for each resource and just let them fill in? Maybe a hundred or so.

Alternatively, I could download the first one, send a request, then download the success and send subsequent requests.

I am using CoreData to update the database, which I suppose means that I need to have a separate NSManagedObjectContent for each request?

I am also interested to know if AFHTTPClient makes callbacks in the main thread or in the thread that initiated the request? I would prefer that the main thread does not block the execution of CoreData I / O.

+4
source share
1 answer

Regarding resource loading, you can use AFNetworking to queue them.

You might be able to use the operation (void) enqueueHTTPRequestOperation: (AFHTTPRequestOperation *) AFHTTPClient.

First create a singleton to save your own AFHTTPClient as follows:

@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 

Then the queue of your requests is:

 // Store the operations in case the failure block needs to cancel them __block NSMutableArray *operations = [NSMutableArray array]; // Add operations for url for (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]; } 

There is also enqueueBatchOfHTTPRequestOperations: progressBlock: completionBlock: if you need to track progress.

AFNetworking Project: https://github.com/AFNetworking/AFNetworking/

AFNetworking Docs: http://afnetworking.org/Documentation/index.html

+2
source

Source: https://habr.com/ru/post/1400180/


All Articles