AFNetworking将数据和图像结合起来发送给PHP

时间:2013-06-28 12:49:16

标签: ios objective-c afnetworking

我(最后)在我的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")发送到我的服务器?

1 个答案:

答案 0 :(得分:2)

multipartFormRequestWithMethod 方法中,有一个名为 parameters 的参数可用于发送一些数据。

例如:

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                            myName, @"name"
                            , secondName, @"twoname"
                            , nil];

NSMutableURLRequest *request = [client multipartFormRequestWithMethod:@"POST" path:@"upload.php" parameters:params constructingBodyWithBlock: ^(id <AFMultipartFormData>formData) {
    [formData appendPartWithFileData: imageToUpload name:@"avatar" fileName:fullFilename mimeType:@"image/png"];
}];