I want to ask how to send an POST Request with body using AFNetworking 3.0. Any help would be much appreciated!
Asked
Active
Viewed 759 times
-1
-
check AFNetworking documentation http://cocoadocs.org/docsets/AFNetworking/3.1.0/Classes/AFHTTPSessionManager.html. you can use convenient method [AFHTTPSessionManager NSURLSessionDataTask *)POST:(NSString *)URLString parameters:(nullable id)parameters success:(nullable void (^)(NSURLSessionDataTask *task, id _Nullable responseObject))success failure:(nullable void (^)(NSURLSessionDataTask * _Nullable task, NSError *error))failure]. – kaushal Jun 12 '16 at 06:18
1 Answers
1
From AFNetworking's GitHub:
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://example.com/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
//Set the request body here
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
Edit
The above answer is useful especially if you want to set a custom request body.
If you only need to POST a simple set of parameters you can do it like this:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
[manager POST:@"http://exaple.com/path" parameters:@{@"param1" : @"foo", @"anotherParameter" : @"bar"} progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
//success block
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//failure block
}];

guidev
- 2,695
- 2
- 23
- 44
-
i want to post a string that is a token only not an image – Mohamad Bachir Sidani Jun 11 '16 at 14:58