NSURLSession send token back to server not working with ios10 - ios

I am trying to use NSURLSession, I had successfully received token from server, now I have to used that Token to get further details...
I had tried below code to get user data..
but I am getting httpResponse code: 500
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *authValue = [arrTokenData valueForKey:#"Token"];
//Configure session with common header fields
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = #{#"bearer": authValue};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSString *url = #"http://test.myserver.am/api/mobile/LookUps/getuserdata";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
if (!error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200)
{
NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:nil];
//Process the data
}
}
}];
[task resume];
I am using iOS 10 , above code is not working, also I have tried several ways but no any success...
I have tried stackoverflow solution but this is also not working out for me...
Please help me out...

Related

Integrate Digest Authentication in Objective c

I want to integrate digest authentication in my objective c code.
I am using NSURLSessionDataTask.
In first webservice call i fetch the nonce value and then in next call i set the header of the same webservice.
NSDictionary *payload;
payload = #{
#"Username" : #"",
#"Password" : #"",
};
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#""]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
[request setHTTPMethod:#"GET"];
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:payload
options:0 error:&error];
request.HTTPBody = data;
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSLog(#"%#", httpResponse);
NSDictionary* dictHeaders = [(NSHTTPURLResponse *)response allHeaderFields];
NSLog(#"%#",[dictHeaders objectForKey:#"Www-Authenticate"]);
[self callWSAfterAuthentication:[dictHeaders objectForKey:#"Www-Authenticate"]];
}
}];
[dataTask resume];
You have not said in your question what exact problems you have. Assuming the authentication simply does not work:
Add a NSURLSessionDelegate to your NSURLSession and handle the authentication in the URLSession:didReceiveChallenge:completionHandler: delegate method. Check for NSURLAuthenticationMethodHTTPDigest and respond accordingly. (You can find info on how to implement this)

how to call again same APIs when response is other then status code 200 or error (some time)

i am using APIs call in my iPhone (objective C) app. my APIS call returns Status code 200, but some time it does return 405 response. when i restart my app i do get proper response.
how to call back same API when i get other then 200 response or if i get error...so that i don't have to restart app again.
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *authValue = [NSString stringWithFormat:#"Bearer %#",
[arrTokenData valueForKey:#"Token"]];
//Configure session with common header fields
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = #{#"Authorization": authValue};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSString *url = #"http://test.myserver.am/api/mobile/LookUps/getuserdata";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
if (!error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200)
{
//Process the data
}
else if
{
// how to call back same API
}
}
else
{
// how to call back same API
}
}];
[task resume];
Thanks in advance
I considered as you created a generic method of network call. If you will get an error or other than 200 response. Just take the request details from your request and call that generic method with that request(URL).
Sample code:
NSURLSessionDataTask *DataTask = [session dataTaskWithRequest:theRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
NSHTTPURLResponse *serverResponse = (NSHTTPURLResponse*)response;
if (error == nil) {
if (serverResponse.statusCode == 200) {
NSString *theXML = [[NSString alloc] initWithBytes:
[data bytes] length:[data length] encoding:NSUTF8StringEncoding];
NSLog(#"%#", theXML);
} else {
NSLog(#"%#, %#", serverResponse.URL, serverResponse.allHTTPHeaderFields);
//Call the generic network call method with the above details again
}
} else {
NSLog(#"%#", error. localizedDescription);
NSLog(#"%#, %#", serverResponse.URL, serverResponse.allHTTPHeaderFields);
//Call the generic network call method with the above details again
}
}];
[DataTask resume];
Create new thread and execute the failed requests.
Create one method and write your code in that method and call same method on error like below
- (void)callService {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
NSString *authValue = [NSString stringWithFormat:#"Bearer %#",
[arrTokenData valueForKey:#"Token"]];
//Configure session with common header fields
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = #{#"Authorization": authValue};
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSString *url = #"http://test.myserver.am/api/mobile/LookUps/getuserdata";
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
if (!error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200)
{
//Process the data
}
else
{
// how to call back same API
[self callService];
}
}
else
{
// how to call back same API
[self callService];
}
}];
[task resume];
}

Not getting data from web service using NSURLSession with POST

When I try to call web service using NSURLSession with POST on Apple Watch, response parameter is nil. What might be the issue with this ?
Code for calling web service:
NSURL *url = [NSURL URLWithString:#"https://demo.test.com:22322/api/Alerts/UpdateAlertStatus?intUserId=5&paramaccessTokenId=24460c5f-be71-45b5-99cf-f46c277c3d9e&UserId=100200"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
request.HTTPMethod = #"POST";
NSMutableDictionary *mutDictParameters = [[NSMutableDictionary alloc] init];
[mutDictParameters setObject:#"708" forKey:#"AlertId"];
[mutDictParameters setObject:#"2878" forKey:#"XmlMessageId"];
[mutDictParameters setObject:#"5" forKey:#"UserId"];
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:mutDictParameters
options:kNilOptions error:&error];
if (!error) {
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request
fromData:data completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
// Handle response here
NSLog(#"Response : %#",response);
}];
[uploadTask resume];
}

Add user information in request

Since ASIHTTPRequest is deprecated, I am migrating my code to use NSURLSession based server communication. Currently, I am using NSDictionary "userInfo" property of ASIHTTPRequest to send additional user information. The description of "userInfo" in ASIHTTPRequest documentation is "Custom user information associated with the request (not sent to the server)".
After the request is processed, I re-fetch this "userInfo" object from the request object and take action accordingly.
My ASIHTTPRequest code example is
Request:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:#"http://www.google.com"];
[request setDelegate:self];
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:1] forKey:#"requestCount"];
[request setUserInfo:userInfo];
I want to achieve same functionality through NSURLSession, how can I do this?
NSURLSession code example:
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: self.queue];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:timeOutSeconds];
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Response:%# %#\n", response, error);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
}
}
}];
[dataTask resume];
Because you are using completion handler so you can use block variable, try below code:
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: self.queue];
NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:timeOutSeconds];
__block NSDictionary *userInfo = [NSDictionary dictionaryWithObjectAndKeys...........];**
NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Response:%# %#\n", response, error);
NSLog(#"UserInfo: %#", userInfo);
if(error == nil)
{
NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"Data = %#",text);
}
}
}];
[dataTask resume];
The cleanest way to go is to subclass NSURLRequest and add the desired property - be it tag, or userInfo and use it the same way you are used to with ASIHTTP framework.

"Authentication Required" with NSURLSession. User/Key correct

I'm new to Objective-C and am struggling to get the following code to work properly. Logging out dataString is telling me that the API is returning an "Authentication Required" message. When I put the resulting URL into a browser, however, the information I want is returned correctly. What am I missing? Is NSURLSession doing something to change the request?
- (void)fetchWX
{
NSString *requestString = [NSString stringWithFormat:#"http://%#:%##flightxml.flightaware.com/json/FlightXML2/Metar?airport=%#", FLIGHTAWARE_USERNAME, FLIGHTAWARE_API_KEY, _airport];
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask = [self.urlSession dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"%#", dataString);
}];
[dataTask resume];
}
There's another method in my app with a similar structure that's working properly, and FlightAware's synchronous example using NSURLConnection also works fine. Just can't seem to use NSURLSession.
NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
config.HTTPAdditionalHeaders = #{ #"Accept":#"application/json"};
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:path];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask = [urlSession dataTaskWithRequest:req completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"jsonObject is %#",jsonObject);
}];
and add this delegate method, which will be called once to resolve the authentication challenge.
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler {
NSString *user = #"YourUserName";
NSString *password = #"YourKey";
NSLog(#"didReceiveChallenge");
// should prompt for a password in a real app but we will hard code this baby
NSURLCredential *secretHandshake = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistenceForSession];
// use block
completionHandler(NSURLSessionAuthChallengeUseCredential,secretHandshake);
}
I have tested it and it worked.

Resources