How to cancel network request with afnetworking - afnetworking

Is there a way to cancel all network request (the request started by another method) before I do a network request with AFNetworking
I tried like below but not work:
- (void)sendRequest:(NSUInteger)page{
NSURL *aUrl = [NSURL URLWithString:#"http://www.abc.com/"];
AFHTTPClient *httpClientToCancel = [[AFHTTPClient alloc] initWithBaseURL:aUrl];
[httpClientToCancel cancelAllHTTPOperationsWithMethod:#"POST" path:#"product/like"];
[httpClientToCancel release];
... start a new request here .....
But not work. I just want to cancel all request (at least the request I wrote above) before I start a new request.
Thank you!

[[httpClient operationQueue] cancelAllOperations];

Don't Create new AFHTTPClient instance.
try "[self cancelAllHTTPOperationsWithMethod:#"POST" path:#"product/like"];

Both the other two answers are right. Don't Create new AFHTTPRequestOperationManager instance
#interface OperateCustomerView () <WYPopoverControllerDelegate>{
AFHTTPRequestOperationManager *manager;// = [AFHTTPRequestOperationManager manager];
}
- (void)viewDidLoad {
[super viewDidLoad];
manager = [AFHTTPRequestOperationManager manager];

Related

IOS - Basic Authentication with a REST API - SSL - AFNetworking 3.0

Everything works great with the code, the problem is it says authentication failed, though the username and password is 100% correct, so not sure if there is a way to pass the login and the password and get the user authenticated
NSString *urlString = #"URL";
NSMutableArray * keyStrings = [NSMutableArray new];
NSMutableArray * valueStrings = [NSMutableArray new];
[keyStrings addObject:#"user"];
[valueStrings addObject:#"abc"];
[keyStrings addObject:#"password"];
[valueStrings addObject:#"12345"];
NSDictionary * requestDict = [[NSDictionary alloc] initWithObjects:valueStrings forKeys:keyStrings];
AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"application/xml"];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
manager.securityPolicy.allowInvalidCertificates = YES;
manager.securityPolicy.validatesDomainName = NO;
I'm guessing you're intending to use HTTP Basic Authentication in which case you should be using the Authorization header field instead of passing the username and password in plain text within the request's parameters (I made this mistake the first time I tried to do Basic Authentication with a REST API).
You will need to add it to the AFHTTPRequestSerializer's headers which you can do by utilizing the setAuthorizationHeaderFieldWithUsername:password: method or by constructing the header field value manually and setting the header field value using the setValue:forHTTPHeaderField: method.

RestKit add custom header for all requests?

I am using RestKit for my iOS app.
I would like to add a custom header for all requests.
Is it possible to add a single header in one place and have all my RestKit requests use it? If so, where do I add the code?
If not - do I have to add a header for every single request I make?
You can set the header on the client that the RKObjectManager creates, after initializing the RKObjectManager:
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:#"https://mycompany.example.com/rest/"];
[[manager HTTPClient] setDefaultHeader:#"X-AUTH-TOKEN" value:#"abc123"];
You don't need to subclass the AFHTTPClient.
It is possible by using custom AFHTTPClient. Create a subclass of AFHTTPClient and rewrite requestWithMethod:path:parameters: method like this:
- (NSMutableURLRequest *)requestWithMethod:(NSString *)method
path:(NSString *)path
parameters:(NSDictionary *)parameters
{
[self setDefaultHeader:#"X-USER-TOKEN" value:userToken];
return [super requestWithMethod:method
path:path
parameters:parameters];
}
Then initialize object manager with it:
RKObjectManager *manager = [[RKObjectManager alloc]
initWithHTTPClient:customHttpClient];

how to add custom header to AFNetworking upload task?

i know how to add headers in normal to GET or POST request but i couldn't add custom header to upload manager
so if any can help me in that thanks
You can try this to add Header..
NSMutableURLRequest * request;
[request setValue:#"Add your value here" forHTTPHeaderField:#"Set field"];
For Example if you want to add cookie, then
[request setValue:#"frontend=322ybbnbgda6382392du" forHTTPHeaderField:#"Cookie"];
If you are using any of these:
AFURLRequestSerialization#multipartFormRequestWithMethod:URLString:parameters:
or
AFURLRequestSerialization#requestWithMultipartFormRequest:...
All of these methods returns a NSMutableURLRequest, to which you can add the headers using NSMutableURLRequest#setValue:forHTTPHeaderField:.
From there you can use a task, executing for example AFURLSessionManager#uploadTaskWithRequest:fromFile:progress:success:failure: or AFURLSessionManager#dataTaskWithRequest:success:failure: to send the request.
Using AFHTTPRequestOperationManager class you can add header.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager.requestSerializer setValue:#"<Your Header String>" forHTTPHeaderField:#"<Key(Parameer Name)>"];

AFNetworking calling clearAuthorizationHeader

I see this method in AFNetworking:
- (void)clearAuthorizationHeader {
[self.mutableHTTPRequestHeaders removeObjectForKey:#"Authorization"];
}
how would I call this method in another file? I tried the following:
#import "AFURLRequestSerialization.h"
AFHTTPRequestSerializer *clear;
and then calling it inside my logout method like so:
[clear.clearAuthorizationHeader];
but I get this error:
/Users/jsuske/Documents/SSiPad(Device Only)ios7/SchedulingiPadApplication/ViewControllers/LHLoginController.m:495:36: Expected identifier
To call a method, you need the space notation instead of a Dot. But you need also a valid object instance of the serializer, which you can get from the AFHTTPRequestOperationManager.
Here is an example code:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestSerializer <AFURLRequestSerialization> * requestSerializer = manager.requestSerializer;
[requestSerializer clearAuthorizationHeader];

AFNetworking 2.0: Passing header information

I am new to AFNetworking and I know how to pass URL parameters. But how would I pass headers into the same call.
I am also subclassing my AFHTTPSessionManager
See my code below:
- (void)getExpenses:(NSString *)page
success:(void (^) (NSArray *myExpenses))success
failure:(RequestFailureBlock)failure
{
NSString *resourceURL = [NSString stringWithFormat:#"%#/expenses/", APIBaseURLString];
NSDictionary *parameters = #{#"page":page, #"Authorization": APIAuthorization};
[self getExpenses:resourceURL parameters:parameters success:success failure:failure];
}
setAuthorizationHeaderFieldWithToken is deprecated due to servers having different requirements about how the access token is sent (token, bearer, etc)
michaels answer otherwise is correct, use
[self.requestSerializer setValue:#"Some-Value" forHTTPHeaderField:#"Header-Field"];
or
[self.requestSerializer setAuthorizationHeaderFieldWithUsername:#"" password:#""];
for basic auth
You set header values on the requestSerializer property of AFHTTPSessionManager:
[self.requestSerializer setValue:#"Some-Value" forHTTPHeaderField:#"Header-Field"];
EDIT:
It looks like you're trying to set authorization; there is a method for that too:
[self.requestSerializer setAuthorizationHeaderFieldWithUsername:#"" password:#""];
// OR
[self.requestSerializer setAuthorizationHeaderFieldWithToken:#""];
If you need to set the Content-Type header, see this SO answer on how to do that

Resources