AFNetworking timeout is not working - ios

I am using AFNetworking V2.5.4.
The default timeout for AFN is 60s, this is too long for my app. I want to set it as 20s.
So I tried follow code manager.requestSerializer.timeoutInterval = 20;
But it's not working. I searched some post saying I need add [manager.requestSerializer willChangeValueForKey:#"timeoutInterval"];
manager.requestSerializer.timeoutInterval = 3;
[manager.requestSerializer didChangeValueForKey:#"timeoutInterval"];
Still, it's not working.
Follow is my code piece
+ (AFHTTPRequestOperation *)sendRequestWithRequest:(NSMutableURLRequest*) request
manager:(AFHTTPRequestOperationManager *)manager
success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure{
[manager.requestSerializer willChangeValueForKey:#"timeoutInterval"];
manager.requestSerializer.timeoutInterval = 3;
[manager.requestSerializer didChangeValueForKey:#"timeoutInterval"];
NSLog(#"manager %#, start time %lf",manager, [[NSDate date] timeIntervalSince1970]);
AFHTTPRequestOperation *operation = [manager HTTPRequestOperationWithRequest:request
success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (operation.response.statusCode) {
success(operation, responseObject);
}else{
failure(operation, nil);
}
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(operation, error);
}];
[manager.operationQueue addOperation:operation];
return operation;}

Related

Sending array of dictionary with afnetworking 2.0

I've a big problem, I'm trying to send an array of dictionary with afnetworking, that's my code:
checkDeliveryParams = #{#"cart_total":#(cart_total),#"shipping":#{#"address":[User sharedInstance].shipping_city,#"country":#"IT",#"postcode":[User sharedInstance].shipping_postcode,#"state":[User sharedInstance].shipping_provincia},#"user_id":#([User sharedInstance].user_id),#"cart_contents":temp};
cart total it's an array like this
(
quantity:1
product_id:2
)
but server receive something like this
(
quantity:1
),
(
product_id:2
)
my request code is
+(void)GET:(NSString *)path
params:(NSDictionary *)params
auth:(BOOL)authenticate
success:(void (^)(NSDictionary* responseObject))success
failure:(void (^)(NSError *error, NSDictionary* responseObject))failure{
NSString *URLString = [#"" stringByAppendingPathComponent:path];
NSLog(#"GET - API URL: %#", URLString);
AFHTTPRequestOperationManager *manager = [Rest commonManager:path sendAuthToken:authenticate];
// manager.requestSerializer=NSJSONSerialization ;
[manager GET:URLString parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responsedata){
NSLog(#"ok della richiesta %#",responsedata);
[Rest verbose:responsedata];
success(responsedata);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"errore della richiesta %#",error.localizedDescription);
failure(error,[Rest parseErrorResponseForOperation:operation]);
}];
}
I've tried a lot of method, I've tried to set nsjonserializer, "application/json", I've already tried to use NSURLSessionDataTask...
Sorry for my English, someone can help me ?
the common manager call in [rest commonManager] is defined in this method
+(AFHTTPRequestOperationManager *)commonManager:(NSString *)path sendAuthToken:(BOOL)sendToken{
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.securityPolicy.allowInvalidCertificates = NO;
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
if([Session isOpen] && [Rest authorizationRequiredForPath:path] && sendToken){
[manager.requestSerializer setValue:[NSString stringWithFormat:#"Bearer %#", [Session token]] forHTTPHeaderField:#"Authorization"];
}
return manager;
}
that's how I send parameters in get call
+(void)GET:(NSString *)path
params:(NSDictionary *)params
auth:(BOOL)authenticate
success:(void (^)(NSDictionary* responseObject))success
failure:(void (^)(NSError *error, NSDictionary* responseObject))failure{
NSString *URLString = [#"" stringByAppendingPathComponent:path];
NSLog(#"GET - API URL: %#", URLString);
AFHTTPRequestOperationManager *manager = [Rest commonManager:path sendAuthToken:authenticate];
// manager.requestSerializer=NSJSONSerialization ;
[manager GET:URLString parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responsedata){
NSLog(#"ok della richiesta %#",responsedata);
[Rest verbose:responsedata];
success(responsedata);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"errore della richiesta %#",error.localizedDescription);
failure(error,[Rest parseErrorResponseForOperation:operation]);
}];
}

How can we pass the parameters along with block methods in objecitve-c

I want to pass the 'NSString' as a parameter for as URLString in below method, how can we do that
-(void)makeServiceCallSuccess:(void (^)(NSDictionary *response))success
failure:(void (^)(NSError *error))failure {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:URLString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
response = (NSDictionary *)responseObject;
success(response);
NSLog(#"JSON: %#", response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(error);
NSLog(#"Error: %#", error);
}];
}
simply add parameter in method, as usually we are doing like
-(void)makeServiceCallSuccessWithURLString:(NSString*)urlString withResponseHandler:(void (^)(NSDictionary *response))success
failure:(void (^)(NSError *error))failure
There is no wat to pass a paramether in that method as it, you can edit it and add a parameter or read a value from aproperty
-(void)makeServiceCallSuccess:(void (^)(NSDictionary *response))success
failure:(void (^)(NSError *error))failure {
NSString* myString = self.myProperty;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:myString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
response = (NSDictionary *)responseObject;
success(response);
NSLog(#"JSON: %#", response);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
failure(error);
NSLog(#"Error: %#", error);
}];
}

AFNetworking 2.0

I'm a newbie in iOS development and I'm trying to figure out how to send GET request with AFNetworking.
I used the example provided in Tutorial on Using AFNetworking 2.0 and placed it in main expecting a error:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://samwize.com/api/poos/"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
...and I've got nothing, so I tried to point to the webservice that returns a valid JSON and also got nothing. Why none of blocks (success or failure) are executed?
Your code does not execute blocks (success or failure) beacause somthing went wrong.
but if you use try catch block then it will go into catch block try once.
code:
try {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:#"http://samwize.com/api/poos/"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}#catch (NSException *exception) {
**// you will get error here**
}
Use following function and just send your URL in Argument
- (void)callWebservice : (NSString *)strURL{
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:[NSURL urlWithEncoding:strURL]];
[httpClient registerHTTPOperationClass:[AFJSONRequestOperation class]];
[httpClient setDefaultHeader:#"Accept" value:#"application/json"];
[httpClient setParameterEncoding:AFJSONParameterEncoding];
NSMutableURLRequest *request = [httpClient requestWithMethod:#"GET" path:#"" parameters:nil];
[request setTimeoutInterval:180];
[AFJSONRequestOperation addAcceptableContentTypes:[NSSet setWithObject:#"text/html"]];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON)
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"Success");
} failure:^ (NSURLRequest *request, NSURLResponse *response, NSError *error, id json){
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"Failure");
}];
[GlobalManager setOperationInstance:operation];
[operation start];
}
It was strange, I just created another project (iOS instead of OSX) and called the same code from the IBAction and it worked easily. In Podfile I specified a new version of AFNetworking (2.5 instead of 2.4). I don't know if this is relevant.
Thank you everyone for trying to help me.
Try following code to do that.
#try {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:stringURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}
#catch (NSException *exception) {
NSLog(#"Exception - %#", [exception debugDescription]);
}
#finally {
}
And make sure you have a valid JSON.

AFNetworking GET request with query is not working

this is always error with -1004 ( could not connect to server )
but the request in browser is working fine.
what's wrong with my code?
(url : "http://localhost:3000/v1/voice/version?appname=wevoice")
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:#"http://localhost:3000/v1/voice/version"
parameters:#{ #"appname": #"wevoice" }
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
You have to set the property baseURL on your request manager. Here is an example:
self.requestManager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:http://localhost:3000];
Later, in your concrete GET message to the manager, you'll only pass the relative URL path:
[self.requestManager GET:#"/v1/voice/version"
parameters:#{ #"appname": #"wevoice" }
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
And keep in mind, that, if you want to send your paramters as JSON, you'll need a request serializer:
self.requestManager.requestSerializer = [AFJSONRequestSerializer serializer];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSMutableDictionary *dic = [NSMutableDictionary dictionary];
[dic setObject:#"wevoice" forKey:#"appname"];
[manager GET:#"http://localhost:3000/v1/voice/version"
parameters:dic
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
You can try this.May be the way you add Parameter is wrong.
Try this method. Hope it helps.
+ (void)getRequestWithURLStringWithSuccess:(void(^)(id object))successBlock andFail:(void(^)(NSString *errorMessage))failBlock {
AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc]initWithBaseURL:[NSURL URLWithString:#"http://localhost:3000/v1/voice/version"]];
NSString *urlString = #"/version";
[manager GET:urlString parameters:#{ #"appname": #"wevoice" } success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
}

AFNetworking 2.0 HTTP POST Progress

How can I get the progress of an AFHTTPRequest? I've tried searching all over the net.
I am using:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"gameId" : datas[0], #"p1": datas[1], #"p2":datas[2], #"turn":datas[3] };
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:#"http://localhost/thepath/isprivate/thefile.php"
parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
}];
Is there like, a property or method I can use to access the progress of an AFNetworking 2.0 HTTP POST?
Try this:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = #{#"gameId" : datas[0], #"p1": datas[1], #"p2":datas[2], #"turn":datas[3] };
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString:#"http://localhost/thepath/isprivate/thefile.php" parameters:params error:&error];
AFHTTPRequestOperation *requestOperation = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"operation success: %#\n %#", operation, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
[requestOperation setUploadProgressBlock:^(NSUInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
double percentDone = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
NSLog(#"progress updated(percentDone) : %f", percentDone);
}];
[requestOperation start];
Hope this helps.
The shortest way way to implement this is
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestOperation *requestOperation = [manager POST:#"/service/user/authenticate" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//Your Business Operation.
NSLog(#"operation success: %#\n %#", operation, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
//Here is the upload progress
[requestOperation setUploadProgressBlock:^(NSUInteger bytesWritten, long long totalBytesWritten, long long totalBytesExpectedToWrite) {
double percentDone = (double)totalBytesWritten / (double)totalBytesExpectedToWrite;
//Upload Progress bar here
NSLog(#"progress updated(percentDone) : %f", percentDone);
}];
You can use following method
- (NSURLSessionUploadTask *)uploadTaskWithRequest:(NSURLRequest *)request
fromData:(NSData *)bodyData
progress:(NSProgress * __autoreleasing *)progress
completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler
of AFHTTPSessionManager class.
UPDATE:
Usually you will prefer to use KVO to get uploading values. So something like following should be used:
static void * kDGProgressChanged = &kDGProgressChanged;
...
[progress addObserver:self
forKeyPath:#"fractionCompleted"
options:NSKeyValueObservingOptionNew
context:kDGProgressChanged];
...
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(__unused NSDictionary *)change
context:(void *)context
{
if (kDGProgressChanged == context) {
dispatch_async(dispatch_get_main_queue(), ^{
[self updateProgressInfo];
});
}
}

Resources