iosobjective-cmultipartform-dataafhttprequestoperation

post method how to send only required parameters objective-c


I am sending multipart data to server text along with images and voice/image and voice are optional in this case when i am not sending the image data or voice the app is crashing please help on this !

-(void)uploadphoto{
 NSString* mid= @"1";
    NSString*userid=@"13"; //[[NSUserDefaults standardUserDefaults] valueForKey:kUserID];

    imageData = UIImagePNGRepresentation (thumbnail.image);

     AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:[NSURL URLWithString:baseURLString]];

    NSDictionary *parameters = @{@"UserID":userid, @"Name": name_TF.text,@"MandalID":mid,@"Address":address_TV.text,@"PinCode":pincode_TF.text,@"Email":emailid_TF.text,@"Dese":grivence_TV.text};

    AFHTTPRequestOperation *op = [manager POST:@"Grievance/CreateRequest" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

    [formData appendPartWithFileData:imageData name:@"file" fileName:@"image.png" mimeType:@"image/png"];

    [formData appendPartWithFileData:audioData name:@"file" fileName:@"Audio.m4a" mimeType:@"audio/.mp4 .m4a"];

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"Success: %@ ***** %@", operation.responseString, responseObject);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@ ***** %@", operation.responseString, error);
    }];
    [op start];

    }
}

Solution

  • AFHTTPRequestOperation *op = [manager POST:@"Grievance/CreateRequest" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {  
    
      if (imageData!=nil) 
        [formData appendPartWithFileData:imageData name:@"file" fileName:@"image.png" mimeType:@"image/png"];
    
    
        if (audioData!=nil) 
        [formData appendPartWithFileData:audioData name:@"file" fileName:@"Audio.m4a" mimeType:@"audio/.mp4 .m4a"];
    
    } success:^ ...
    

    In case of while you not send image or audio your imagedata & audiodata contains nil ( you can't send image or audio which have nil data).