I want to send data on server using AFNetworking. I want to send NSData not json parameter. Can anyone suggest how can I send NSData on server using AFNetworking?
You can use this method in AFHTTPRequestOperationManager
- (AFHTTPRequestOperation *)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
The way that you would use the method is:
[self POST:#"http://myurl.com" parameters:#{} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
// attach the NSData to `formData`
} success:^(NSURLSessionDataTask *task, id responseObject) {
// Handle Success
} failure:^(NSURLSessionDataTask *task, NSError *error) {
// Handle Error
}];
In order to attach the data you could use this method in the AFMultipartFormData protocol
- (void)appendPartWithFormData:(NSData *)data
name:(NSString *)name;
Related
I've inherited some Objective-C code from 2013: so old that it used AFNetworking 1.0!
#implementation AFClaimNotificationAPIClient
+ (AFClaimNotificationAPIClient *)sharedClient {
static AFClaimNotificationAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[AFClaimNotificationAPIClient alloc] initWithBaseURL:[NSURL URLWithString:kClaimNotificationURL]];
});
return _sharedClient;
}
- (void) submit:(ClaimNotification *) claimNotification
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure {
NSMutableURLRequest *request = [self multipartFormRequestWithMethod:#"POST" path:kClaimNotificationURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[self populateFormDataForJson:formData andClaimNotification:claimNotification];
[self populateFormDataWithAttachemnts:formData andClaimNotification:claimNotification];
}];
AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request];
DDLogVerbose(#"%#", request.HTTPBody);
[operation setCompletionBlockWithSuccess:success failure:failure];
[operation start];
}
In the corresponding header file for this class, the AFClaimNotificationAPIClient is defined thus:
#interface AFClaimNotificationAPIClient : AFHTTPClient
and AFHTTPClient no longer exists. It was dropped in AFNetworking 2.0, which came out shortly after this code was written.
After much forum searching, I've actually managed to get it partially working again by upgrading to AFNetworking 2.0, and redefining AFClaimNotificationAPIClient as an AFHTTPSessionManager:
#interface AFClaimNotificationAPIClient : AFHTTPSessionManager
My submit button code now looks like this:
- (void) submit:(ClaimNotification *) claimNotification
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure {
NSURLSessionDataTask *request = [self POST:kClaimNotificationURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[self populateFormDataForJson:formData andClaimNotification:claimNotification];
[self populateFormDataWithAttachemnts:formData andClaimNotification:claimNotification];
} success:^(NSURLSessionDataTask *task, id responseObject) {
DDLogVerbose(#"Post success");
// handle success
} failure:^(NSURLSessionDataTask *task, NSError *error) {
DDLogVerbose(#"Post error");
}];
// [operation start];
[request resume]; // [request start] doesn't work
}
I chose AFHTTPSessionManager as the new type for my class because it's the only one that I could find that contains the constructingBodyWithBlock definition, and I was trying to keep the code as close to the original as possible.
Amazingly enough, my reworked code actually posts data to the server and gets a reply. However, the app hangs at that point because the calling code (not shown here) is not receiving a success (or failure) message. I can see that I've removed a whole step from the original code - the setting up of the operation variable and then the triggering of its setCompletionBlockWithSuccess method.
You need to execute the block according to the response passing a responseObject or an error with the corresponding operation
try this
- (void) submit:(ClaimNotification *) claimNotification
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure {
NSURLSessionDataTask *request = [self POST:kClaimNotificationURL parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[self populateFormDataForJson:formData andClaimNotification:claimNotification];
[self populateFormDataWithAttachemnts:formData andClaimNotification:claimNotification];
} success:^(NSURLSessionDataTask *task, id responseObject) {
DDLogVerbose(#"Post success");
// handle success
success(nil,responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
DDLogVerbose(#"Post error");
failure(nil, error);
}];
// [operation start];
[request resume]; // [request start] doesn't work
}
You can use AFHTTPRequestOperation as well and this will return both parameters needed in your callbacks
I have class that manages connections with AFNetworking.
So I want to call my function like NSDictionary *dict = [ServerManager requestWithURL:#"https://someurl.com"];
And that's the function in the other class:
- (NSDictionary *) requestWithURL:(NSString *)requestURL {
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
[manager GET:requestURL parameters:nil progress:nil
success:^(NSURLSessionDataTask *operation, id responseObject){
return responseObject;
}
failure:^(NSURLSessionDataTask *operation, NSError *error) {
}];
}
I know that is incorrect to do that. So what should I do to return responseObject back to NSDictionary *dict? I'd like to get the basic idea of asynchronous development with blocks.
Since the networking request completes long after its is launched, the only way to handle the result is with a block passed to your request method...
// when request completes, invoke the passed block with the result or an error
- (void)requestWithURL:(NSString *)requestURL completion:(void (^)(NSDictionary *, NSError *))completion {
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
[manager GET:requestURL parameters:nil progress:nil success:^(NSURLSessionDataTask *operation, id responseObject){
if (completion) completion((NSDictionary*)responseObject, nil);
}, failure:^(NSURLSessionDataTask *operation, NSError *error) {
if (completion) completion(nil, error);
}];
}
Make it public in a ServerManager.h
- (void)requestWithURL:(NSString *)requestURL completion:(void (^)(NSDictionary *, NSError *))completion;
Elsewhere, call it:
[ServerManager requestWithURL:#"http://someurl.com" completion:^(NSDictionary *dictionary, NSError *error) {
// check error and use dictionary
}];
TL;DR : Clone and check leak yourself https://github.com/JakubMazur/SO41343532/
I have a one class that handle all my networking. It's called ResponseOrganizer and in there I have a class method:
+ (void)getSth:(void (^)(NSURLSessionDataTask *operation, NSArray *locales, id plainObject))success failure:(void (^)(NSURLSessionDataTask *operation, NSError *error))failure {
Connection *connection = [Connection new];
connection.urlString = #"http://sample-file.bazadanni.com/download/txt/json/sample.json";
connection.requestMethodType = GET;
[connection fireWithSuccess:^(NSURLSessionDataTask *operation, NSArray *returnArray, id originalResponse) {
success(operation, returnArray, originalResponse);
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
failure(operation, error);
}];
}
Where Connection is a single my internal connection object:
Here is the implementation:
#import "Connection.h"
#interface Connection()
#property (weak,nonatomic) AFHTTPSessionManager *manager;
#end
#implementation Connection
#pragma mark - Connection groundwork
-(void)fireWithSuccess:(void (^)(NSURLSessionDataTask *operation, NSArray* returnArray, id originalResponse))success failure:(void (^)(NSURLSessionDataTask *operation, NSError *error))failure {
self.manager = [AFHTTPSessionManager manager];
[self.manager urlString:self.urlString withMethod:self.requestMethodType parameters:self.paramaters success:^(NSURLSessionDataTask *operation, id responseObject) {
success(operation,#[responseObject],nil);
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
failure(operation,error);
}];
}
#end
And I have a category calling right method inside AFNetworking. To simplify it look like this:
-(void)urlString:(NSString*)urlString withMethod:(RequestMethodType)method parameters:(NSDictionary*)parameters success:(void (^)(NSURLSessionDataTask *operation, id responseObject))success failure:(void (^)(NSURLSessionDataTask *operation, NSError *error))failure {
switch (method) {
case GET: {
[self getWithURLString:urlString parameters:parameters success:^(NSURLSessionDataTask *operation, id responseObject) {
success(operation,responseObject);
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
failure(operation,error);
}];
break;
}
}
And when I want to make request for example in my ViewController I make it like this:
[ResponseOrginizer getSth:^(NSURLSessionDataTask *operation, NSArray *locales, id plainObject) {
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
}];
And when I run it in instrument I'm always getting:
And it here doesn't matter it will land on success/failure block, it always cause a leak. I extract everything from this and put it on github as simple as possible. Github link:
https://github.com/JakubMazur/SO41343532/
The leak appears here:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
It seems that the reason is the same (or similar) as discussed here - NSURLSession holds a retained reference to the delegate.
Change you code in Connection.m like this to avoid the leak:
-(void)fireWithSuccess:(void (^)(NSURLSessionDataTask *operation, NSArray* returnArray, id originalResponse))success failure:(void (^)(NSURLSessionDataTask *operation, NSError *error))failure {
AFHTTPSessionManager *manager = [Connection manager];
[manager urlString:self.urlString withMethod:self.requestMethodType parameters:self.paramaters success:^(NSURLSessionDataTask *operation, id responseObject) {
success(operation,#[responseObject],nil);
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
failure(operation,error);
}];
}
+ (AFHTTPSessionManager*) manager
{
static dispatch_once_t onceToken;
static AFHTTPSessionManager *manager = nil;
dispatch_once(&onceToken, ^{
manager = [AFHTTPSessionManager manager];
});
return manager;
}
If you need to handle multiple sessions, you may use another approach: call -[AFHTTPSessionManager invalidateSessionCancelingTasks:] when you're done with the session, e.g.:
-(void)fireWithSuccess:(void (^)(NSURLSessionDataTask *operation, NSArray* returnArray, id originalResponse))success failure:(void (^)(NSURLSessionDataTask *operation, NSError *error))failure {
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager urlString:self.urlString withMethod:self.requestMethodType parameters:self.paramaters success:^(NSURLSessionDataTask *operation, id responseObject) {
success(operation,#[responseObject],nil);
[manager invalidateSessionCancelingTasks:YES];
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
failure(operation,error);
[manager invalidateSessionCancelingTasks:YES];
}];
}
(Note: pass YES if you want to cancel pending tasks, NO otherwise).
Some time, my server slow to response and I got this message in response, The Operation couldn't completed.(NSURLErrorDomain error -1004)
How to handle such errors?
P.S. I'm using AFNetworking for this.
You may increase the time-out by overriding the get/post methods
Following is the example for get method
- (AFHTTPRequestOperation *)GET:(NSString *)URLString
parameters:(id)parameters
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure
{
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:#"GET" URLString:[[NSURL URLWithString:URLString relativeToURL:self.baseURL] absoluteString] parameters:parameters error:nil];
[request setTimeoutInterval:ADD_YOUR_TIME_OUT_INTERVAL];
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:success failure:failure];
[self.operationQueue addOperation:operation];
return operation;
}
P.S. I used this approach in the previous version of AFNetwork, by subclassing AFHTTPClient. I didn't test it in the new version's AFHTTPRequestOperationManager.
This may be helpful : https://stackoverflow.com/a/22666837/1292441
I'm using AFHTTPRequestOperationManager for a POST request. Now I'm deliberately entering incorrect information to handle a 400 error code. Now, the web service actually returns a JSON with a message explaining to the user what they've done wrong. I would very much like to get this JSON to display the message in a UIAlertView. However, the failure block of:
[operationManager POST:ServerURL parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: Status Code: %d", operation.response.statusCode);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failed: Status Code: %d", operation.response.statusCode);
}];
doesn't pass down a responseObject like the one in the success block. So does anyone know how I can access the JSON returned by the Web Service with the 400 error? The NSError *error simply gives me Request failed: bad request (400) and not the JSON returned.
Any help would be appreciated,Mike
Looking at the code for - responseObject, it appears that an HTTP error prevents it from being populated. You can grab the responseData directly and parse it yourself, but I would say this is either a bug or a good enhancement request. (It looks like - responseObject probably should be checking self.responseSerializationError, not self.error, when deciding if it should try to build a response object.)
You can do either of these solutions
1) Set the acceptableStatusCodes to accept your 400 statusCode, and you handle in the success block
manager.responseSerializer.acceptableStatusCodes = [NSIndexSet indexSetWithIndex:400];
2) Create a custom ResponseSerializer, like this JSONResponseSerializerWithData, to insert the responseObject into the NSError userInfo, and handle in the failure block
Pro tip: AFNetworking is opensource, just take a look at AFHTTPRequestOperation for methods
setCompletionBlockWithSuccess:failure:
responseObject
error
I also faced same problem in AFNetworking, as instead of using
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
progress:(void (^)(NSProgress * _Nonnull))uploadProgress
success:(void (^)(NSURLSessionDataTask * _Nonnull, id _Nullable))success
failure:(void (^)(NSURLSessionDataTask * _Nullable, NSError * _Nonnull))failure
Please try to use that one :-
- (NSURLSessionDataTask *)POST:(NSString *)URLString
parameters:(id)parameters
constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
progress:(nullable void (^)(NSProgress * _Nonnull))uploadProgress
success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure
thanks,
Following code worded for me:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"parse-application-id-removed" forHTTPHeaderField:#"X-Parse-Application-Id"];
[manager.requestSerializer setValue:#"parse-rest-api-key-removed" forHTTPHeaderField:#"X-Parse-REST-API-Key"];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
manager.securityPolicy.allowInvalidCertificates = YES;
NSString *URLString = [NSString stringWithFormat:#"%#/%#", BASE_URL,methodName];
[manager POST:URLString parameters:requestDict success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
[myDelegate StopIndicator];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
[myDelegate StopIndicator];
}];