gpt4 book ai didi

ios - AFNetworking 结合数据和图像发送到 PHP

转载 作者:行者123 更新时间:2023-11-28 22:31:22 24 4
gpt4 key购买 nike

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

最佳答案

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"];
}];

关于ios - AFNetworking 结合数据和图像发送到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17365104/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com