NSUrlSession iso NSUrlConnection - uploading device token to a MySQL Database - nsurlsession

I'm trying to update my code from NSUrlConnection to NSUrlSession. The app is running fine, no errors, but the token is never uploaded to the MySQL database... I've really no idea? Should I implement delegates or am I doing something basic stuff very wrong here? :-)
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"deviceToken"];
//Information is only uploaded to SQLite database if 'deviceToken' is not null
if ([deviceToken length] > 0) {
NSURL *url = [NSURL URLWithString:#"http://sampleUrl.com/do.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *varString = [NSString stringWithFormat:#"deviceToken=%#", deviceToken];
NSData *requestData = [varString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
/*NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:request fromData:requestData completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
//Handle
}];*/
//NSURLSessionUploadTask *uploadTask2 = [session uploadTaskWithStreamedRequest:request];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
//Handle
}];
[dataTask resume];
Any ideas?
Thanks and regards,
Tom

I solved the problem:
NSString *deviceToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"deviceToken"];
//Information is only uploaded to SQLite database if 'deviceToken' is not null
if ([deviceToken length] > 0) {
// Create URL and URLRequest
NSURL *url = [NSURL URLWithString:#"http://url.com/something.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
//Create the body
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *varString = [NSString stringWithFormat:#"deviceToken=%#", deviceToken"]];
// Create POST parameters and add it to HTTPBody
[request setHTTPMethod:#"POST"];
[request setHTTPBody: [varString dataUsingEncoding:NSUTF8StringEncoding]];
// Set up a simple and asynchronous NSURLSession to send data to the php
// Set up the session configuration and header data
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
[config setRequestCachePolicy:NSURLRequestUseProtocolCachePolicy];
[config setHTTPAdditionalHeaders:#{
#"Accept" : #"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
#"Content-Type" : #"application/x-www-form-urlencoded",
#"Content-Length" : [NSString stringWithFormat:#"%lu", (unsigned long)[[varString dataUsingEncoding:NSUTF8StringEncoding] length]]
}];
// Create the session and the task
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
if (error)
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
if (response)
{
NSLog(#"response description: %#", response.description);
[prefs setBool:YES forKey:#"tokenSent"];
}
if (data)
NSLog(#"data description: %#", data.description);
}];
// Start the task
[task resume];
}
Regards,
Tom

Related

Storing JSON response in iOS error

I am making a call to an online php from my iOS app. In my output window I see the JSON Response with the data. But I need to store the NSString in my userdefaults but it is coming up NULL.
In this code the NSLog(#"JSON Response is %#", responseData); returns the json data just fine and I see the ipixid. But in the NSLog (#"ipixid is %#", ilixid); it returns ipixid is (null)
NSString *post =[[NSString alloc] initWithFormat:#"email=%#", strValue];
NSLog(#"PostData: %#",post);
NSURL *url1=[NSURL URLWithString:#"http://www.ipixsocial.com/membership/getresult.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url1];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"JSON Response is %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
// NSString *username = [(NSString *) [jsonData objectForKey:#"email"]init];
NSInteger success = [(NSNumber *) [jsonData objectForKey:#"uid"] integerValue];
NSString* ipixid = [jsonData objectForKey:#"ipixid"];
[[NSUserDefaults standardUserDefaults] setObject:ipixid forKey:#"ipixid"];
NSLog (#"ipixid is %#", ipixid);
Don't ignore the "error" parameter you're passing to the parser. Also check that "jsonData" is not nil. I'm think that parsing is failing and because you're ignoring it and assuming jsonData is valid you're getting nil for [jsonData objectForKey:#"ipixid"];

NSURLConnection send null data to server

I send a registration message to the server like this:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/html" forHTTPHeaderField:#"Content-Type"];
[request setValue:API_KEY forHTTPHeaderField:#"api_key"];
NSString *dataString = [NSString stringWithFormat:#"username=%#&password=%#", username, encryptedPassword];
NSData *data = [dataString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
// Connection
NSURLResponse *response = nil;
NSError *error = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
// Print results
NSLog(#"response: %#", response);
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(#"response: %d", [(NSHTTPURLResponse *)response statusCode]);
}
id jsonObject = [NSJSONSerialization JSONObjectWithData:returnData options:0 error:&jsonError];
NSLog(#"jsonObject: %#", jsonObject);
The connection was success, but I got the error response:
=> response: 400
=> jsonObject: {
error = "Please provide username.USERNAME:";
}
The server received a null user name, but I'm sure I pass a valid user name to http body (converted into NSData). The data contains the following info (converted back into string):
username=cc24#cc.com&password=12345678nW7wMNio0bsNBHGqY7VgSw%3D%3D
I don't what happened. But the API works fine with Android app.

Rest kit VS ASIHTTPRequest

I am using "RestKit 0.20.3` in my project,
due to some crucial reasons I am going to convert all my API calls to Ret kit,
please can any one tell me how can I make a same call like below with rest kit
I am sending my ASIHHTP code
please can any one migrate it to Rest kit, I unable to find the way
NSDictionary *dictionary=....;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#auth/login",KBASEURL]];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setValidatesSecureCertificate:NO];
[request addRequestHeader:#"Content-Type" value:#"application/json; charset=utf-8"];
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dataDictionary options:kNilOptions error:nil];
[request setPostBody:(NSMutableData *)jsonData];
[request setContentLength:[jsonData length]];
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:#"https://172.22.221.117/api/v1.0/"]];
NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:#"abc.com",#"email",#"password",#"password", nil];
[manager postObject:nil
path:#"auth/login"
parameters:dictionary
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
if(operation.HTTPRequestOperation.response.statusCode==200){
//do your processing
}
}];

How to give two json request to two different api at a time from one page and from one method

I am working on my new iPhone application,in that I need the datas and addresses from one url and from anther url I need to get the images. These two results are in the form of json response data but I am getting only the result for the datas....
Here is my code
- (void)viewDidLoad
{
jsondataimg=[[NSMutableString alloc] initWithString:#""];
#####for this url i'm not getting the result##########
NSString *urlimg = [NSString stringWithFormat:#"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=%#",name];
//NSLog(#"%#",urlimg);
NSURL *url1= [NSURL URLWithString:urlimg];
NSURLRequest *request1 = [[NSURLRequest alloc] initWithURL: url1];
NSURLConnection *connection1 = [[NSURLConnection alloc] initWithRequest:request1 delegate:self];
jsonData = [[NSMutableString alloc] initWithString:#""];
NSString *urlString = [NSString stringWithFormat: #"https://maps.googleapis.com/maps/api/place/details/json?reference=%#&sensor=false&key=your key",selectedname];
NSLog(#" the name is%#",selectedname);
NSLog(#" the reference is%#",selectedrefer);
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
[connection1 release];
[request1 release];
[super viewDidLoad];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *partialData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSString *partialData1 = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[jsondataimg appendString:partialData1];
[jsonData appendString:partialData];
[partialData release];
[partialData1 release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
# pragma mark for fetching the image urls
NSDictionary *imageurls=[jsondataimg JSONValue];
NSDictionary*images=[imageurls objectForKey:#"responseData"];
NSLog(#"%#",images);
##########here null value is displaying#######
#pragma mark for fetching the datassss
NSDictionary *filesJSON = [jsonData JSONValue];
NSDictionary *address1 = [filesJSON valueForKey:#"result"];
NSLog(#"Found %#",address1);
}
Just use this no need to set delegate methods nsurl connections.. you will get the data...and same for next one.
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=mumbai"]]];
NSURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *strResponse = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// NSLog(#"%#",strResponse);
SBJSON *sbJason = [[SBJSON alloc] init];
NSMutableDictionary *getPlaceList = [sbJason objectWithString:strResponse];

send parameter values and retrieve an xml file Xcode

In my current xcode project, I need to send parameter values to a url and need to retrieve an xml file based on the parameter values sent.
I tried the below code but it's not working:
(IBAction)myButtonClick:(id)sender
{
NSURL *oRequestURL =
[NSURL URLWithString:#"http://xyz .com/air/1.0/search?from=MAA&to=CJB&depart-date=2012-06-30&adults=2&children=2&infants=1&way=one&cabin-type=Economy&sort=asc"];
NSMutableURLRequest *oRequest = [[[NSMutableURLRequest alloc]init]autorelease];
[oRequest setHTTPMethod:#"POST"];
[oRequest setURL: oRequestURL];
NSMutableData *oHttpBody = [NSMutableData data];
[oHttpBody appendData:[#"This is HTTP Request body" dataUsingEncoding:NSUTF8StringEncoding]];
[oRequest setValue:[oHttpBody length] forHTTPHeaderField:#"Content-Length"];
NSError *oError = [[NSError alloc]init];
NSHTTPURLResponse *oResponseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:oRequest returningResponse:oResponseCode error:oError];
if ([oResponseCode statusCode]> 200) {
NSLog(#"Status code is greater than 200");
}
NSString *strResult=[[NSString alloc]initWithData:oResponseData encoding:NSUTF8StringEncoding];
NSLog(#"The result is %s",strResult);
}
I have searched many sites and books but could not find a solution.
Would be of great help if a link to a tutorial or some other useful resource can be provided. Appreciate your great help.
Thank You.
Hi,
I have found the solution. The code is as below. Hope it helps someone else:)
- (IBAction)myButtonPressed:(id)sender
{
NSString *urlAsString = #"http://api.abc.com/air/1.0/search?from=MAA&to=CJB&depart-date=2012-09-30&adults=2&children=2&infants=1&way=one&cabin-type=Economy&sort=asc";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setValue:#"2193141de2g7e2a34bb19bc3aa52b3b5" forHTTPHeaderField:#"X-XX-API-KEY"];
[urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:#"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection
sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if ([data length]>0 &&
error == nil)
{
NSString *html = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"HTML = %#", html);
}
else if ([data length]== 0 && error==nil) {
NSLog(#"Nothing was downloaded");
}
else if (error!= nil) {
NSLog(#"Error occured = %#", error);
}
}];
}

Resources