2014-09-11 85 views
0

這是我的要求。 Web服務需要在輔助線程上調用以將人員數據作爲字典數組發送。 ({名稱:PERSON1, 地址:印度 照片:一個路徑1 }; {名稱:PERSON2, 地址:印度 照片:一個路徑2 } ) 在本作的照片,我們還有其他的Web服務,我們上傳圖片並獲得回覆路徑。其他線程內的輔助線程

我做了什麼。 寫了一個函數並在輔助線程上調用它並啓動了一個活動指示器。 函數for循環正在製作這個字典。它工作正常。 但是當我同步上傳圖像時,活動指示燈停止。如果我異步執行操作,那麼當我獲得路徑響應時,我的main for循環就消失了,我沒有字典對象來添加路徑。

-(BOOL)callSynchWebService 
{ 
__block BOOL validateFlag=NO; 
MBProgressHUD * progressHud = [[MBProgressHUD alloc] initWithView:self.view]; 

InterNetConnectionService *netService=[[InterNetConnectionService alloc]init]; 
if(![netService checkFornetConnectionWithStatus]) 
{ 
    [self.view addSubview:progressHud]; 
    progressHud.mode = MBProgressHUDModeIndeterminate; 
    progressHud.labelText = @"Loading"; 
    [progressHud show:YES]; 
    for (Person *p in array_persons) 
    { 
     NSMutableDictionary *dict=[[NSMutableDictionary alloc]init]; 
      [dict setObject:p.name forKey:@"Name"]; 
      [dict setObject:p.address forKey:@"Address"]; 
      NSString *photoResult=[self sendingPhototoServer:p.image]; 
      [dict setObject:photoResult forKey:@"Photo"]; 
    } 
    } 

然後用ASIHTTP發送這個數組。

請你幫助我在這個for循環中異步上傳圖像並將其響應存儲在字典中。

謝謝。

回答

0

這裏是我的想法如何解決你的嵌套網絡請求中的問題。所有網絡請求都是異步的。

UIImage *image = [UIImage imageNamed:@"example"]; 
NSArray *originalArray = @[@{@"name": @"person1", @"image": image, @"address": @"india"}, 
          @{@"name": @"person1", @"image": image, @"address": @"india"}, 
          @{@"name": @"person1", @"image": image, @"address": @"india"}]; 
__block NSMutableArray *uploadArray = [NSMutableArray array]; 
for (NSDictionary *item in originalArray) { 
    //use AFNetworking here 
    //all network request in AFNetworking is asynchronous 
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 
    [manager POST:@"example.com/imageupload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
     NSData *data = UIImagePNGRepresentation(item[@"image"]); 
     [formData appendPartWithFileData:data name:@"pic" fileName:@"image.png" mimeType:@"image/png"]; 
    } success:^(NSURLSessionDataTask *task, id responseObject) { 
     [uploadArray addObject:@{@"name": @"person1", 
           @"imagePath":responseObject[@"url"], 
           @"address":@"india"}]; 
     if (uploadArray.count == originalArray.count) { 
      [manager POST:@"example.com/arrayupload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { 
       // convert the uploadArray to json or other and add to http body 
      } success:^(NSURLSessionDataTask *task, id responseObject) { 
       //finished 
      } failure:^(NSURLSessionDataTask *task, NSError *error) { 
       //upload failed 
      }]; 
     } 
    } failure:^(NSURLSessionDataTask *task, NSError *error) { 
     //upload failed 
    }]; 
} 

如果您需要在網絡請求期間阻止主線程,請添加HUD。

希望這個可以指導你在這個問題上