Storing JSON response in iOS error - xcode

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"];

Related

NSUrlSession iso NSUrlConnection - uploading device token to a MySQL Database

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

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.

pass local declaration of NSDictionary to performSelector

How it do so that I will not need to put data object right in selector call method?
code with warning (Local declaration of data) :
NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:#"SiluetaImage", #"ACTION", silueta_id, #"siluetaid", siluetaTyp_id, #"siluetatypid", nil];
[self performSelector:#selector(downloadBinDataForTyp:data:)
withObject:#"SiluetaImage"
withObject:data];
code without warning :
[self performSelector:#selector(downloadBinDataForTyp:data:)
withObject:#"SiluetaImage"
withObject:[NSDictionary dictionaryWithObjectsAndKeys:#"SiluetaImage", #"ACTION", silueta_id, #"siluetaid", siluetaTyp_id, #"siluetatypid", nil]];
the selector:
- (void)downloadBinDataForTyp:(NSString *)typ data:(NSDictionary*)data
{
ASINetworkQueue *q = [self queue];
NSString *sUrl = #"url_web_service";
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:sUrl]];
NSString *msgLength = [NSString stringWithFormat:#"%d", [[self getMsg] length]];
[request setTimeOutSeconds:60];
[request addRequestHeader: #"Content-Type" value:#"text/xml; charset=utf-8"];
[request addRequestHeader: #"SOAPAction" value:_action];
[request addRequestHeader: #"Content-Length" value:msgLength];
[request setRequestMethod: #"POST"];
request.userInfo = data;
[request appendPostData:[self getMsg]];
[request setDelegate:self];
[q addOperation:request];
[q go];
}
NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys:#"SiluetaImage", #"ACTION", silueta_id, #"siluetaid", siluetaTyp_id, #"siluetatypid", nil];
[self performSelector:#selector(downloadBinDataForTyp:data:)
withObject:#"SiluetaImage"
withObject:data];
In this you are passing data whose scope is just to the method. And outside the method it can not be accessed, as it is getting released.

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];

Xcode, can't send UTF-8 Text

I am trying to send a post value to my server.
It successfully send English characters.
This code is for finding friend, and it can't send UTF-8 text.
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope{
/*
Update the filtered array based on the search text and scope.
*/
if(![searchText isEqualToString:#""]){
NSUserDefaults * userdef = [NSUserDefaults standardUserDefaults];
NSString *encodedSearchText = [searchText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString * uploadUrl = [NSString stringWithFormat:#"%#/%#" , GPON_URL , GPON_URL_SEARCHFRIEND];
NSURL *url = [NSURL URLWithString:uploadUrl];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:encodedSearchText forKey:#"u_id"];
[request setPostValue:[userdef objectForKey:KEY_USER_ID] forKey:#"s_username"];
[request startSynchronous];
[request setShouldAttemptPersistentConnection:NO];
NSString *response = [request responseString];
SBJsonParser * parser = [[[SBJsonParser alloc] init] autorelease];
NSDictionary * json = (NSDictionary *)[parser objectWithString:response];
[searchMember removeAllObjects];
if( [[json objectForKey:#"result"] isEqual:#"YES"] ){
[searchMember addObjectsFromArray:[json objectForKey:#"data"]];
[self.tableView reloadData];
}
}
}
here is my code. can you see what cause the error?
You don't appear to be setting the string encoding of the request; try:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setStringEncoding:NSUnicodeStringEncoding];
Also, this is a very poor way of determining if an NSString is empty:
if (![searchText isEqualToString:#""])
Use the length method instead:
if ([searchText length] > 0)

Resources