AFNetworking 2.0比1.3慢

时间:2014-03-21 22:37:46

标签: ios performance batch-processing afnetworking-2

使用AFNetworking 1.3升级我的应用程序后,现在似乎下载相同的文件需要更长的时间。这是使用AFNetworking 1.3.x批量操作下载4个文件的日志:

2014-03-21 19:29:23.775 <my_app>[2056:60b] 4 / 4
2014-03-21 19:29:23.777 <my_app>[2056:60b] 4 / 4
2014-03-21 19:29:23.778 <my_app>[2056:60b] 4 / 4
2014-03-21 19:29:23.779 <my_app>[2056:60b] 4 / 4

这是使用AFNetworking 2.0的相同文件的日志

2014-03-21 19:31:15.616 <my_app>[2068:60b] 1 of 4 complete
2014-03-21 19:31:15.876 <my_app>[2068:60b] 2 of 4 complete
2014-03-21 19:31:16.065 <my_app>[2068:60b] 3 of 4 complete
2014-03-21 19:31:17.244 <my_app>[2068:60b] 4 of 4 complete

如您所见,使用v1.3.x比使用2.0快得多。下面是我在v2.0上使用的代码:

NSMutableArray *tempOperations = [[NSMutableArray array] init];
NSArray *tempUrls = [[NSArray alloc] initWithObjects: obj1, obj2, obj3, obj4, nil];

for (id urlTemp in tempUrls){
    //Create NSURLRequest
    NSURL *url = [[NSURL alloc] initWithString:urlTemp];
    NSMutableURLRequest *finalrequest = [[NSMutableURLRequest alloc] initWithURL:url];

    // AFNetworking Request
    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:finalrequest];
    [operation setResponseSerializer:[AFHTTPResponseSerializer new]];

    // Add request to array
    [tempOperations addObject:operation];
}

NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:tempOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
    NSLog(@"%lu of %lu complete", numberOfFinishedOperations, totalNumberOfOperations);
} completionBlock:^(NSArray *operations) {
    for (AFHTTPRequestOperation *ro in operations) {

        if (ro.error) {

            NSLog(@"++++++++++++++ Operation error: %@", ro.error);

        }else {

            NSLog(@"Operation OK: %@", [ro.request URL]);

        }
    }
}];
[[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];

1 个答案:

答案 0 :(得分:0)

好吧,我找到了一个解决方案,而不是以前的工作方式,但我的效果会更好。更改是使用initWithBaseURL创建AFHTTPRequestOperationManager的实例,这似乎可以提高请求的速度。

AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:@"<url>"]];
[manager setResponseSerializer:[AFHTTPResponseSerializer new]];

for (id urlTemp in tempUrls){
    [manager GET:urlTemp parameters:nil success:^(AFHTTPRequestOperation *ro, id responseObject) {
        NSLog(@"Operation OK: %@", [ro.request URL]);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
}];