Best architecture for an iOS application that makes many network requests?

前端 未结 4 1851
-上瘾入骨i
-上瘾入骨i 2020-12-12 09:31

I\'m in the process of rethinking my approach to the request architecture of a large app I\'m developing. I\'m currently using ASIHTTPRequest to actually make requests, but

4条回答
  •  囚心锁ツ
    2020-12-12 09:44

    Here is how I generally do it. I, too, have a singleton object used for making network requests. For requests that have to be made often, I have an NSOperationQueue that accepts AFHTTPRequestOperations (or AFJSONRequestOperations) since I generally use AFNetworking for making requests. For these, there is a completionBlock and failureBlock property that is executed upon success or failure of the request. On my singleton object, I would have a method for initiating a particular network request, and as parameters to that method, I would include a success and failure block which can be passed into the blocks defined in the method. This way, the entire application can make a network request, and the scope of the application at that point is available to the singleton in the block that is passed to the method. For example...(using ARC)

            @implementation NetworkManager
    
        -(void)makeRequestWithSuccess:(void(^)(void))successBlock failure:(void(^)(NSError *error))failureBlock
    
        {
            NSURL *url = [NSURL URLWithString:@"some URL"];
    
            NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
            AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
            [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
                [responseObject doSomething];
    
                if (successBlock)
                    dispatch_async(dispatch_get_main_queue(), successBlock);
    
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    
                if (failureBlock)
                    dispatch_async(dispatch_get_main_queue(), ^{
                        failureBlock(error);
                    });
            }];
    
            [self.operationQueue addOperation:op];
        }
    @end
    

    And you can always make the success block take whatever parameters you need to pass around.

提交回复
热议问题