我(终于)在我的 iOS 项目中使用了 afnetworking。我已经成功地将POST
数据和图像发送到我的 php 服务器,但是在单独的代码块中。
发送数据:
NSDictionary *parameters = [NSDictionary dictionaryWithObjectsAndKeys:myname,@"name", mysencondname, @"twoname", nil];
NSURL *url = [NSURL URLWithString:@"http://DOMAIN.COM"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];
[httpClient defaultValueForHeader:@"Accept"];
[httpClient postPath:@"post.php" parameters:parameters
success:^(AFHTTPRequestOperation *operation, id response) {
NSLog(@"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);
[self requestDone:[operation.response statusCode]];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error with request");
NSLog(@"%@",[error localizedDescription]);
[self requestFailed];
}];
发送图片:
NSData *imageToUpload = UIImagePNGRepresentation(_imageView.image);
AFHTTPClient *client= [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://www.DOMAIN.com"]];
NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"upload.php" parameters:nil constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
[formData appendPartWithFileData: imageToUpload name:@"avatar" fileName:fullFilename mimeType:@"image/png"];
}];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *response = [operation responseString];
NSLog(@"response: [%@]",response);
[MBProgressHUD hideHUDForView:self.view animated:YES];
[self dismissViewControllerAnimated:YES completion:NULL];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if([operation.response statusCode] == 403){
NSLog(@"Upload Failed");
[MBProgressHUD hideHUDForView:self.view animated:YES];
return;
}
NSLog(@"error: %@", [operation error]);
}];
我的问题是如何将它们组合起来,以便我可以myname, @"name", mysencondname, @"twoname"
通过单个请求将图像和一些数据(如())发送到我的服务器?