使用AFNetworking将5张图像上传到服务器

时间:2016-03-06 09:48:18

标签: ios objective-c afnetworking

我在我的应用程序中使用了Afnetworking,我需要将5个图像发布到服务器,5个图像作为数组,这个数组是我的**请求参数之一。 这是正确的方法还是错误的,还有比它更多的表现吗? -

(IBAction)sPActionButton:(id)sender {
    NSUserDefaults *def=[NSUserDefaults standardUserDefaults];
    NSString * language=[def objectForKey:@"Language"];
     NSString * deviceToken=[def objectForKey:@"dT"];
    [par setObject:deviceToken forKey:@"dT"];
    NSString *check=[def objectForKey:@"Log"];
    [par setObject:check forKey:@"aT"];
    //---------------------------------------------
    NSString * apiKey=APIKEY;
    [par setObject:apiKey forKey:@"aK"];
    [par setObject:language forKey:@"lG"];

    NSMutableArray *images = [NSMutableArray arrayWithCapacity:10];
    for (int x=0; x<_chosenImages.count; x++) {
       NSData *imageData = UIImageJPEGRepresentation(_chosenImages[x], 0.5);
       NSLog(@"%@",imageData);
        NSString *str=[Base64 encode:imageData];
       [images addObject:str];
    }
    NSLog(@"%@",images);
    [par setObject:images forKey:@"image[array]"];
    if ([self validateAllFields]) {

        NSLog(@"par = %@",par);
        //-----------------------------------------------
        [MBProgressHUD showHUDAddedTo:self.view  animated:NO];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        [manager POST:[NSString stringWithFormat:@"%@/sellPrp?",BASEURl] parameters:par
              success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             NSLog(@"JSON: %@", responseObject);
         }
              failure:^(AFHTTPRequestOperation *operation, NSError *error) {

                  UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error Retrieving Data"
                                                                      message:[error localizedDescription]
                                                                     delegate:nil
                                                            cancelButtonTitle:@"Ok"
                                                            otherButtonTitles:nil];
                  [alertView show];
                  [MBProgressHUD hideHUDForView:self.view  animated:NO];
              }];

    }
}

1 个答案:

答案 0 :(得分:0)

- (void)prepareForImagePosting
{


if (imageCount < self.arrAllPostImages.count)//arrAllPostImages array contains images for posting and imageCount acts as iterator
{
   NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];       //Prepare the dictionary which contains image for posting
     [dict setObject:@"1" forKey:@"upload"];
     [dict setObject:[[self.arrAllPostImages objectAtIndex:imageCount]objectForKey:@"SelectedPhoto"] forKey:@"post_image"];
[self postImage:dict];
}
else  
return;
}




 - (void)postImage: (NSMutableDictionary *)dictPostImages
  {
        NSError *error = nil;
        NSString *url = POSTIMAGELINK;

        NSMutableDictionary *postDict = [[NSMutableDictionary alloc]init];

     [postDict setObject:[dictPostImages objectForKey:@"upload"]   forKey:@"upload"];

        NSData *jsonRequestDict = [NSJSONSerialization dataWithJSONObject:postDict options:NSJSONWritingPrettyPrinted error:&error];

     NSString *jsonCommand = [[NSString alloc] initWithData:jsonRequestDict encoding:NSUTF8StringEncoding];
        NSLog(@"***jsonCommand***%@",jsonCommand);


     NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:jsonCommand,@"requestParam", nil];

     AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];

    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];

     [manager POST:url parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
     {



    if (isEnteredInFailureBlock == NO)
             {
                 //here Image is posted
   NSData *postPicData=UIImageJPEGRepresentation([dictPostImages   objectForKey:@"post_image"], 0.5) ;

                 [formData appendPartWithFileData:postPicData
                                             name:@"post_image"
                                         fileName:[NSString stringWithFormat:@"image%d.jpg",imageCount]
                                         mimeType:@"image/*"];

             }
             else
             {

             }

    } success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             NSError *error = nil;
             NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
             NSLog(@"Request Successful, response '%@'", responseStr);
             NSMutableDictionary *jsonResponseDict = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:&error];
             NSLog(@"Response Dictionary:: %@",jsonResponseDict);
     if ([[jsonResponseDict objectForKey:@"status"] intValue] == 1)
             {
                 if (isEnteredInFailureBlock == NO)
                 {
                     [self.arrSuccessfullyPostedImagesDetails addObject:jsonResponseDict];

                     if (appDel.successfullImgPostingCount == appDel.totalPostingImagesCount)
                     {
     }
                     else
                     {
                         appDel.successfullImgPostingCount++;

                         imageCount++;

                         [self prepareForImagePosting];
                     }

                 }

                 else
                 {
                     self.arrSuccessfullyPostedImagesDetails = [[NSMutableArray alloc]init];
                     appDel.successfullImgPostingCount = 0;
                     appDel.totalPostingImagesCount = 0;
                     imageCount = 0;
                     return;
                 }

    }

             else
             {
                 self.arrSuccessfullyPostedImagesDetails = [[NSMutableArray alloc]init];
                 appDel.successfullImgPostingCount = 0;
                 appDel.totalPostingImagesCount = 0;
             }

        }
        failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             NSLog(@"Request Error: %@", error);

                isEnteredInFailureBlock = YES;

            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Alert!" message:@"Posting Unsuccessful" delegate:nil cancelButtonTitle:@"ok" otherButtonTitles:nil, nil];
            [alert show];

    // if image is not successfully posted then the server is informed with @"upload" @"0" so that the entire post is deleted from server

        NSMutableDictionary *failureDict = [[NSMutableDictionary alloc]init];

            [failureDict setObject:@"0" forKey:@"upload"];

            [self postImage:failureDict];
         }];

    }