2016-09-24 2 views
0

Мне нужно ударить сотни запросов одновременно с загрузкой файлов. Я использую AFNetworking, и я просто вызываю метод из цикла for. Но это дает мне внутреннюю ошибку сервера в некоторых файлах. На стороне сервера ничего нет. Этот процесс успешно выполняется из Интернета.Хит сотни запросов одновременно с использованием AFNetworking

Вот мой код:

for (UIImage *img in imgages) { 
     [self uploadImage:img]; 
     } 


-(void) uploadImage:(UIImage *)image 
{ 



    // NSDictionary *[email protected]{x:x } 
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:someData 
                 options:0 

                 error:nil]; 

     NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[BASE_URL stringByAppendingString:@"xyz.com"] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
     [formData appendPartWithFormData:jsonData name:@"abc"]; 

     if (imgData) { 

      [formData appendPartWithFormData:imgData name:@"file"]; 

     } 
    } error:nil]; 

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]]; 

    NSURLSessionUploadTask *uploadTask; 

    manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 

    uploadTask = [manager 
        uploadTaskWithStreamedRequest:request 
        progress:nil completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) { 

        }]; 

    [uploadTask resume]; 

} 

Что бы быть лучшим способом для реализации выше функциональности?

+1

Какая у вас ошибка? iOS имеет ограничение на одновременный запрос для каждого хоста, но если это то, что вы испытываете, вы будете получать тайм-ауты от чрезмерных запросов. – Avi

+1

попробуйте использовать 'dispatch_apply' вместо fo-loop – Enix

+0

@Vikas Просьба принять ответ, если его рабочий –

ответ

1

Попробуйте использовать нижеприведенный код для одновременной загрузки файлов.

-(id)init { 
self = [super init]; 
if(self) { 
    backgroundQueue = dispatch_queue_create("com.bgqueue", NULL); 

    dispatch_once(&onceToken, ^{ 

     NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.Demo-Upload"]; 
     sessionConfiguration.HTTPMaximumConnectionsPerHost = 10; 
     manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:sessionConfiguration]; 
    }); 
} 
return self; 
} 

- (void)processFiles{ 
    for (UIImage *img in imgages) { 
     dispatch_async(backgroundQueue, ^(void) { 
      [self uploadImage:img]; 
     }); 
    } 
} 


-(void) uploadImage:(UIImage *)image 
{ 
    // Prepare a temporary file to store the multipart request prior to sending it to the server due to an alleged 
    // bug in NSURLSessionTask. 
    NSString* tmpFilename = [NSString stringWithFormat:@"%f", [NSDate timeIntervalSinceReferenceDate]]; 
    NSURL* tmpFileUrl = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:tmpFilename]]; 

    // Create a multipart form request. 
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[BASE_URL stringByAppendingString:@"xyz.com"] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
    [formData appendPartWithFormData:jsonData name:@"abc"]; 

     if (imgData) { 
      [formData appendPartWithFormData:imgData name:@"file"]; 
     } 
    } error:nil]; 

    // Dump multipart request into the temporary file. 
    [[AFHTTPRequestSerializer serializer] requestWithMultipartFormRequest:request 
              writingStreamContentsToFile:tmpFileUrl 
                completionHandler:^(NSError *error) 
    { 
      // Once the multipart form is serialized into a temporary file, we can initialize 
      // the actual HTTP request using session manager. 


      // Here note that we are submitting the initial multipart request. We are, however, 
      // forcing the body stream to be read from the temporary file. 

      self.uploadTask = [manager uploadTaskWithRequest:request 
           fromFile:tmpFileUrl 
           progress:^(NSProgress * _Nonnull uploadProgress) 
              { 
               NSLog(@"Progress… %f", uploadProgress.fractionCompleted); 
              } 
           completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) 
              { 
               // Cleanup: remove temporary file. 
               [[NSFileManager defaultManager] removeItemAtURL:tmpFileUrl error:nil]; 

               // Do something with the result. 
               if (error) 
               { 
               //Print Error 
               } else 
               { 
                //Print responseObject 
               } 
              }]; 
     // Start the file upload. 
     [self.uploadTask resume]; 
    }]; 
} 

Выше функция будет продолжать загружать изображения, когда приложение переходит на задний план. Таким образом, это не даст вам внутренней ошибки сервера или любой ошибки тайм-аута.

Надеюсь, это поможет вам. И если у вас есть какие-либо сомнения относительно вышеуказанного кода, пожалуйста, не стесняйтесь спрашивать.

Смежные вопросы