send image along with other parameters with AFNetworking

后端 未结 2 718
我在风中等你
我在风中等你 2020-12-05 20:21

I am updating an old application code which used ASIHTTPRequest with AFNetworking. In my case, I am sending a bench of data to API, th

2条回答
  •  天命终不由人
    2020-12-05 20:46

    I have used same AFNetworking to upload image with some parameter. This code is fine working for me. May be it will help out

    NSData *imageToUpload = UIImageJPEGRepresentation(uploadedImgView.image, 1.0);//(uploadedImgView.image);
    if (imageToUpload)
    {
        NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:keyParameter, @"keyName", nil];
    
        AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://------"]];
    
        NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"API name as you have" parameters:parameters constructingBodyWithBlock: ^(id formData) {
            [formData appendPartWithFileData: imageToUpload name:@"image" fileName:@"temp.jpeg" mimeType:@"image/jpeg"];
        }];
    
        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject)
         {
             NSDictionary *jsons = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
             //NSLog(@"response: %@",jsons);
    
         }
                                         failure:^(AFHTTPRequestOperation *operation, NSError *error)
         {
             if([operation.response statusCode] == 403)
             {
                 //NSLog(@"Upload Failed");
                 return;
             }
             //NSLog(@"error: %@", [operation error]);
    
         }];
    
        [operation start];
    }
    

    Good Luck !!

提交回复
热议问题