How to fetch data from webserver using JSON in iphone - iphone

i want to fetch data from webserver using JSON and webservice and then parse the JSON Response string.
then i need to insert the data which i have obtained from the webserver into sqlite database.
i have done posting the data to server api database through HTTP post method and this is working properly and my data is getting saved to my server database.And the response that i get is in this format:
{"TokenID":"od28Denamu","isError":false,"ErrorMessage":"","Result":[{"UserId":"153","FirstName":"Rocky","LastName":"Yadav","Email":"rocky#itg.com","ProfileImage":null,"ThumbnailImage":null,"DeviceInfoId":"12"}],"ErrorCode":900}
i need to parse json data and save it in my local sqlite database which consist the same database table as of the server database
this is my code :
//this is used to post the data to web server database through HTTP POST method
-(void)sendRequest
{
UIDevice *device = [UIDevice currentDevice];
NSString *udid = [device uniqueIdentifier];
NSString *sysname = [device systemName];
NSString *sysver = [device systemVersion];
NSString *model = [device model];
NSLog(#"idis:%#",[device uniqueIdentifier]);
NSLog(#"system nameis :%#",[device systemName]);
NSLog(#"System version is:%#",[device systemVersion]);
NSLog(#"System model is:%#",[device model]);
NSLog(#"device orientation is:%d",[device orientation]);
NSString *post = [NSString stringWithFormat:#"Loginkey=%#&Password=%#&DeviceCode=%#&Firmware=%#&IMEI=%#",txtUserName.text,txtPassword.text,model,sysver,udid];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSLog(#"%#",postLength);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
//this is my web server api method which consist of 5 parameters Loginkey,Password,DeviceCode,Firmware,IMEI
Loginkey takes Username of user
Password takes password of user
DeviceCode takes device model
Firmware takes device Version
IMEI takes uniqueidentifier of device.
[request setURL:[NSURL URLWithString:#"http://192.168.0.68:91/JourneyMapperAPI?RequestType=Login"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
webData = [[NSMutableData data] retain];
NSLog(#"%#",webData);
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[webData release];
}
//this is used to fetch the data through JSON .
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//NSString *loginStatus = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
NSString *loginStatus = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSLog(#"%#",loginStatus);
self.webData = nil;
NSArray* latestLoans = [(NSDictionary*)[loginStatus JSONValue] objectForKey:#"Login"];
[loginStatus release];
//get latest loan
NSDictionary* loan = [latestLoans objectAtIndex:0];
//fetch the data
NSString* fundedAmount = [loan objectForKey:#"Loginkey"];
NSString* loanAmount = [loan objectForKey:#"Password"];
NSLog(#"this is foundedamount:%#",fundedAmount);
NSLog(#"this is loanAmount:%#",loanAmount);
//float outstandingAmount = [loanAmount floatValue] - [fundedAmount floatValue];
//NSString* name = [loan objectForKey:#"name"];
//NSString* country = [(NSDictionary*)[loan objectForKey:#"location"] objectForKey:#"country"];
//set the text to the label
//label.text = [NSString stringWithFormat:#"Latest loan: %# from %# needs another $%.2f, please help",
//name,country,outstandingAmount
// ];
//greeting.text = loginStatus;
[loginStatus release];
[connection release];
[webData release];
}
But the problem when i fetching the data through JSON code is not working,posting to server is working properly.
When i fetch data NSLOG(#"this is foundedamount:null") value is shown .What may be the problem.Please help me in solving this problem.
Thanks

If your problem is to parse a json string, why don't you use a simple json library such as https://github.com/stig/json-framework ?

Related

HTTP-connection with credentials to get HTML document

I would like to download an HTML documents(s) to parse the content. The server asks before entering this site to put in my user credentials. In Java I arrived with a basic authentication in an asynchronous task like this (JSoup):
String base64login = new String(Base64.encodeBase64(loginDaten.getBytes()));
Document parsableDoc = Jsoup.connect(myUrl).header("Authorization","Basic"+base64login)
.timeout(3000)
.get();
but in Objective-C it doesn't work so simple as I thought. Here I want to save the website in an NSData-Object or something similar (for example NSString). Got any ideas to solve this as simple as possible? (I'm such a pro in this sector as you can seeā€¦)
You can do this using the NSURLConnection class ad NSMutableURLRequest. The idea is that you let the NSMutableURLRequest know what kind of auth method you want to use, and the credentials (login/password).
The following code should do it. (You will need the NSdata category for base64Encoding in this link http://cocoadev.com/wiki/BaseSixtyFour )
self.receivedData = [[NSMutableData alloc] init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"login",#"password"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64Encoding]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if ([self.receivedData length] >0)
NSString *result = [[NSString alloc] initWithData:downloadedData encoding:NSUTF8StringEncoding];
NSLog(#"The HTML String Is : %#", result);
{

Do we need to give the request type either "json/xml"

My client is given one web service for my registration. I need to post the values.
I am using the following code to post:
-(IBAction)testingPurpose:(id)sender{
NSMutableDictionary *finalQuoteDict = [[NSMutableDictionary alloc] init];
[finalQuoteDict setValue:#"It is an Error Message" forKey:#"ErrorMsg"];
[finalQuoteDict setValue:#"json" forKey:#"ReturnVal"];
[finalQuoteDict setValue:#"john#live.com" forKey:#"Email"];
[finalQuoteDict setValue:#"David John" forKey:#"FullName"];
[finalQuoteDict setValue:#"2147483647" forKey:#"UserID"];
[finalQuoteDict setValue:#"john" forKey:#"UserName"];
[finalQuoteDict setValue:#"qqqqqq" forKey:#"UserPassword"];
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *jsonRequest = [jsonWriter stringWithObject:finalQuoteDict];
jsonRequest = [jsonRequest stringByReplacingOccurrencesOfString:#"<" withString:#""];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#Register",MainUrl1,jsonRequest]];
NSLog(#"url is---%#",url);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSError* error = nil;
NSURLResponse* response;
NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *dataString=[[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding];
NSMutableDictionary *getResponseDict = [[NSMutableDictionary alloc] init];
[getResponseDict addEntriesFromDictionary:[dataString JSONValue]];
}
But it throws an error says
"Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised leading character\" UserInfo=0x856ac50 {NSLocalizedDescription=Unrecognised leading character}"
Please check the image i.e, to post the values..
Do we need to give the request type either "json/xml"
Thanks a lot in advance
Try to use this
Here httpMethod is "POST".
postData is all ur Post data with Key value same as for web service request.
aUrl is ur service url
-(void)WebService:(NSString *)httpMethod DataDictionary:(id)postData RequestAction:(NSString *)aUrl
{
// Check internet Connection
//Use Reachability class for this==============
Reachability *r = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
NSLog("No Internet Connection Available");
return;
}
self.identifier = serviceIdentifier;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:aUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0 ];
NSLog(#"final request is %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//set body in JSON formate
[request setHTTPBody:[[self convertToJSON:postData] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *contentLength = [NSString stringWithFormat:#"%d",[[request HTTPBody] length]];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
self.responseData = [NSMutableData data]; //Its a mutable Data object
}
}
//Convert data into JSOn format
//use JSON classes for this
-(NSString *)convertToJSON:(id)requestParameters
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestParameters options:NSJSONWritingPrettyPrinted error:nil];
NSLog(#"JSON DATA LENGTH = %d", [jsonData length]);
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON STR LENGTH = %d", [jsonString length]);
return jsonString;
}
//you will get response in NSURLConnection
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog("Failed to get Result......");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *jsonString = [[[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding] autorelease];
NSDictionary *aDic = [jsonString JSONValue];
NSLog("Your Response Data is ==>> %d",aDic);
}
Hope this will helps you
You don't need to supply json or xml in request type unless or until webservice requires it explicitly. It would be better if webservice handles it.
But i think problem is in parsing the response.
First make sure that dataString is not null or empty or you are getting some response from the server.
If it has some values then probably the return value or server response is not a valid JSON format.
You can validate json response by pasting it to the
http://jsonlint.com/ .

Uploading video file to the URL

I am trying to upload video file to the specified URL. When I press button video file should upload into the URL which I used. But no response is coming.
NSString *filePath = [[NSBundle mainBundle]pathForResource:#"3idiots" ofType:#"mov"];
NSURL *uploadurl=[NSURL URLWithString:#"http://115.111.27.206:8081/vblo/upload.jsp"];
//NSData *postVideoData = [NSData dataWithContentsOfFile:filePath];
NSData *postVideoData = [string dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postVideoLength = [NSString stringWithFormat:#"%d", [postVideoData length]];
NSMutableURLRequest *request12 = [[[NSMutableURLRequest alloc] init] autorelease];
[request12 setURL:uploadurl];
[request12 setHTTPMethod:#"POST"];
[request12 setValue:postVideoLength forHTTPHeaderField:#"Content-Length"];
[request12 setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request12 setHTTPBody:postVideoData];
NSURLConnection *theConnection12 = [[NSURLConnection alloc] initWithRequest:request12 delegate:self];
if( theConnection12 )
{
webData12 = [[NSMutableData data] retain];
}
else
{
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData12 setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData12 appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *loginStatus12 = [[NSString alloc] initWithBytes: [webData12 mutableBytes] length:[webData12 length] encoding:NSUTF8StringEncoding];
NSLog(loginStatus12);
if(loginStatus12)
{
UIAlertView *statusAlert12 = [[UIAlertView alloc]initWithTitle:nil message:(NSString *)loginStatus12 delegate:self cancelButtonTitle:#"cancel" otherButtonTitles:nil];
[statusAlert12 show];
}
}
you need to send the request, add this line after you set the HTTPBody
NSData *serverReply = [NSURLConnection sendSynchronousRequest: request12 returningResponse:&response error:&error];

connection didReceiveData called twice while posting a Url in iphone?

I am new to iphone development.I have posted the URL with the user-name and password. I am able to print the data in "connection didReceiveData " method.But i see "connection didReceiveData" method called twice.I don't know ,where i am going wrong. Here is my code
- (void)viewDidLoad {
[super viewDidLoad];
NSString *post = [NSString stringWithFormat:#"&domain=school.edu&userType=2&referrer=http://apps.school.edu/navigator/index.jsp&username=%#&password=%#",#"xxxxxxx",#"xxxxxx"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://secure.school.edu/login/process.do"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data{
NSString *string = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSLog(#"the data %#",string);
}
The whole HTML page is printed twice in the console.So please help me out.Thanks.
You may receive the response data in chunks, which is why NSURLConnection's documentation states:
"The delegate should concatenate the contents of each data object delivered to build up the complete data for a URL load."
Use an instance of NSMutableData for this and only process the complete data once you receive the -connectionDidFinishLoading: message.
As MacOS Developer Library states, connection:didReceiveData can be called multiple times if data is received in chunks. That means you have to save all the chunks in some variable and do data processing in connectionDidFinishLoading method. e.g.
NSMutableData *receivedData = [[NSMutableData alloc] init];
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
[receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data, for example log:
NSLog(#"data: %#", [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]
}

How can I make a website as an iPhone native application?

I'm planning to convert my website into an iPhone native application. I'm stuck at the point of how to achieve this.
Initially, I have developed the first screen i.e., LOGIN screen of my application. My server is built in Java. I'm able to send the login credentials to the server and able to see the request on the server. But I'm unable to receive the response from the server for the request I've sent.
A part of my code is:
NSString *post = #"username=";
post = [post stringByAppendingString:username];
post = [post stringByAppendingString:#"&password="];
post = [post stringByAppendingString:password];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://mysite.com/login.action?"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
// [request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn)
{
receivedData = [[NSMutableData data] retain];
NSLog(#"In \"LOGIN()\" : receivedData = %#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
NSLog(#"In \"didReceiveResponse()\" : receivedData = %#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSString *ReturnStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"In \"didReceiveData()\" : receivedData = %#",receivedData);
NSLog(#"Return String : %#", ReturnStr);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
NSString *urlData;
if (nil != receivedData) {
urlData = [[[NSString alloc] initWithData:receivedData
encoding:NSUTF8StringEncoding] autorelease];
}
NSLog(#"In \"connectionDidFinishLoading()\" : urlData = %#",urlData);
[receivedData release];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
[connection release];
[receivedData release];
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
How do I develop a LOGIN application?
I'm sending a request successfully to the server but I'm unable to get the response from the server. How can I overcome this issue?
If your experience is with web development you may be interested in looking at NimbleKit for iPhone. It's a simple XCode plugin that allows you to use HTML and JavaScript to develop the entire native application.