I am new in the ios field, Now i am trying to implement MKMapView Based iPhone Application. From the Google Map Web web service i Fetch the Data in JSON Output Format.
- (void)update {
self.responseData=[NSMutableData data];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://maps.googleapis.com/maps/api/directions/json?origin=Ernakulam&destination=Kanyakumari&mode=driving&sensor=false"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
-(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{
[connection release];
self.responseData =nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"connection established");
[connection release];
NSString *responseString=[[NSString alloc]initWithData:self.responseData encoding:NSUTF8StringEncoding];
self.responseData=nil;
NSLog(#" OUTPUT JSON DATA^^^^^^^^^^^^^^^^%#",responseString);
}
I got the out put has in the JSON Format. Now i want to draw route between this two location. sow how can i separate all the latitude and Longitude points from the JSON out put Data.
Check out this code. I am using JSONkit for parsing
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(#"connection established");
[connection release];
NSString *responseString=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSMutableDictionary *data1 = [responseData objectFromJSONData];
NSMutableArray *ad = [data1 objectForKey:#"routes"];
NSMutableArray *data2 = [[ad objectAtIndex:0] objectForKey:#"legs"];
NSMutableArray *data3 = [[data2 objectAtIndex:0] objectForKey:#"steps"];
// NSLog(#"Data3 %#", data3);
for(int i = 0; i<data3.count;i++){
NSLog(#"Start %#", [[data3 objectAtIndex:i] objectForKey:#"start_location"]);
NSLog(#"End %#", [[data3 objectAtIndex:i] objectForKey:#"end_location"]);
}
}
I am using SBJson to parse json data.
In general, call [responseString JSONValue] to get parsed data.
You can google it for detail reference.
Related
As I'm a newbie in iOS development, please help me to parse the JSON output.
My JSON output:
{"sbi":[{"Emp_Id":1001,"Emp_Name":"James","Designation":"Manager","Skills":["C,C++"]},{"Emp_Id":1002,"Emp_Name":"John","Designation":"Asst.Manager","Skills":["Java,PHP"]},{"Emp_Id":1003,"Emp_Name":"Joe","Designation":"Chief Manager","Skills":["Oracle,HTML"]}]}
When we launch an app, I should get sbi on the first view and if I select that particular row, I should get all the details related to sbi on the next view, i.e. EmpId, EmpName, Designation, Skills, ...
Thanks in advance.
Parse the json to a dictionary object with
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:yourJson options:0 error:nil];
Please refer following link to Json parsing Demo.It will help you to learn Json parsing.
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
-(void)Startconnection:(NSString *)urlString
{
NSLog(#"%#",urlString);
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:"your url string "]];
connetion1=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self] ;
webData = [NSMutableData data];
}
-(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
{
// [ShowAlert showMyAlert:#"Network Alert" :#"No Internet connection detected"];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSError *myError = nil;
responceDic=nil;
responceDic = [NSJSONSerialization JSONObjectWithData:webData options:NSJSONReadingMutableLeaves error:&myError];
NSLog(#"%#",responceDic );
}
In the .h file declare NSXMLParserDelegate delegate
#interface webservice : NSObject<NSXMLParserDelegate>
{
NSMutableData * webData;
NSString *currentData;
NSURLConnection * connetion1;
}
I am working on a web service app and i have a question. I am calling a specific Url site with the following code:
NSURL *Url = [NSURL URLWithString:[requestStream stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSString *htmlString = [NSString stringWithContentsOfURL:Url encoding:NSUTF8StringEncoding error:&error];
Then i create an nsstring and print it with the NSLog and i got the following results:
2014-05-14 15:50:58.118 jsonTest[1541:907] Data : Array
(
[url] => http://sheetmusicdb.net:8000/hnInKleinenGruppen
[encoding] => MP3
[callsign] => SheetMusicDB.net - J
[websiteurl] =>
)
My question in how can i parse the URL link and then use it as a value? I tried to put them to an array or a dictionary but i get error back. So if anyone can help me i would appreciate it.
Ok i managed to grab the link with the following code:
if(htmlString) {
//NSLog(#"HTML %#", htmlString);
NSRange r = [htmlString rangeOfString:#"=>"];
if (r.location != NSNotFound) {
NSRange r1 = [htmlString rangeOfString:#"[encoding]"];
if (r1.location != NSNotFound) {
if (r1.location > r.location) {
_streamTitle = [htmlString substringWithRange:NSMakeRange(NSMaxRange(r), r1.location - NSMaxRange(r))];
NSLog(#"Title %#", _streamTitle);
}
}
}
} else {
NSLog(#"Error %#", error);
}
Thank you for your suggestions. My problem now is that i pass the string into an avplayer and i can't hear music.
I think this will be help for you..
// #property (nonatomic,retain) NSMutableData *responseData;
// #synthesize responseData;
NSString *urlString=#"http:your urls";
self.responseData=[NSMutableData data];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:urlString]] delegate:self];
NSLog(#"connection====%#",connection);
JSON Delegates :
-(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
{
self.responseData=nil;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSArray *response_Array = [NSJSONSerialization JSONObjectWithData:self.responseData options:kNilOptions error:nil];
// Write code for retrieve data according to your Key.
}
Try This:
NSString *urlStr=[NSString stringWithFormat:#"uRL"];
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
if (theConnection)
{
receivedData=[[NSMutableData data] retain] ;
}
#pragma mark - Connection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
// append the new data to the receivedData
// receivedData is declared as a method instance elsewhere
//NSLog(#"data %#",data);
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// release the connection, and the data object
// [connection release];
// [receivedData release];
UIAlertView *prompt = [[UIAlertView alloc] initWithTitle:#"Connection Failed" message:[error localizedDescription]delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[prompt show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *content = [[NSString alloc] initWithBytes:[receivedData bytes]
length:[receivedData length] encoding: NSUTF8StringEncoding];
NSData *jsonData = [content dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}
}
i have a PHP webservices. My requirement is using PHP web services to display json data in UIView one by one.
The Json data is :
"id\":\"6\",\"title\":null,\"description\":null,\"year\":\"2012\",\"date\":null}","{\"id\":\"4\",\"title\":\"
correct in the year 2013\",\"description\":\"<\/font> Financial
system in America for this year is not indicated progress this year
too. More problems will creep up. \r\n<\/font> Aggressive stage
of Telangaana agitation- formation of seperate Telangaana state-
bifurcation of state - sure indications are \r\n\r\npredicted.
\r\n*<\/font> The Gujarath CM - Sri Narendra Modi - Bright future
is indicated. \r\n*<\/font> Still danger is indicated for
Indoneshia and Sumitra Islands.
i want to display these data in UIView.Before display each line of data displaying * symbol.How to retrieve and how to display in UIViewcontroller.Help me any body.Thanks in advance.
I am writing like this.but i got exception.
-(void)loadData
{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults valueForKey:#"id"];
[defaults valueForKey:#"title"];
[defaults valueForKey:#"description"];
[defaults synchronize];
NSURL *url=[NSURL URLWithString:#"http://www.predictions.php"];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
[[NSURLConnection alloc]initWithRequest:request delegate:self];
urlConnection=[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData=[[NSMutableData alloc]init];
[responseData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if(connection==urlConnection)
{
strResponse=[[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#",strResponse);
NSError *error;
jsonDict=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",jsonDict);
NSArray *arrResults=[jsonDict valueForKey:#"id"];
NSLog(#"%#",arrResults);
arrString=[NSMutableArray array];
for(NSDictionary *dictRes in arrResults)
{
constants *con=[[constants alloc]init];
con.titl=[dictRes valueForKey:#"title"];
// con.desc=[dictRes valueForKey:#"description"];
[arrString addObject:con];
}
[View1 reloadData];
}
}
You can use NSJSONSerialization class for parsing JSON objects.
Hope this helps.
You should use this framework: https://github.com/stig/json-framework and SBJsonParser class to parse the JSON script. The below code will help you parse json response:
SBJSON *parser = [[SBJSON alloc] init] ;
NSDictionary *dic = (NSDictionary *)[parser objectWithString:respString error:nil];
This code will convert your response string in the respString variable into an NSDictionary, and now you can extract each object by calling:
NSString* response = [dic objectForKey:#"response"];
I want to update my json file in ios app which is offline compiled in the app. When the app is refreshed the file should get updated from the server : localhost:8888/ios/ios_app/Service/data.json
Please help...
Thank you in advance
I use SOAP when i need get value that can be serialized to a string type. But if all what you need is json file, look at NSURLConnection class.
- (void)downloadJSONFromURL {
NSURLRequest *request = ....
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
// ...
}
NSData *urlData;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
urlData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[urlData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *jsonParsingError = nil;
id object = [NSJSONSerialization JSONObjectWithData:urlData options:0 error:&jsonParsingError];
if (jsonParsingError) {
DLog(#"JSON ERROR: %#", [jsonParsingError localizedDescription]);
} else {
DLog(#"OBJECT: %#", [object class]);
}
}
Please do the following to reproduce the problem
NSString *url = #"http://qdreams.com/laura/index.php?request=EventWeekListings&year=2012&month=10&day=22";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSString *json = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"%#" , json);
NSDictionary *deserializedData = [json objectFromJSONString];
deserializedData would contain nil. Expected behavior is to return proper dictionary.
Is that because total number of JSON dictionary elements exceed a certain threshold?
I would appreciate any help in this matter.
Why not just use the NSJSONSerialization method JSONObjectWithData:options:error: it worked fine for me.
NSString *url = #"http://qdreams.com/laura/index.php?request=EventWeekListings&year=2012&month=10&day=22";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
NSArray *arr = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"%#",arr);
After Edit: I ran the code again this morning, and like you I got null. The problem with dataWithContentsOfURL. is that you have no control and no way to know what happened if something went wrong. So, I retested with the code below:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[self loadData];
}
-(void) loadData {
NSLog(#"loadData...");
self.receivedData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:#"http://qdreams.com/laura/index.php?request=EventWeekListings&year=2012&month=10&day=22"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10.0];
[NSURLConnection connectionWithRequest:request delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"didReceiveResponse...");
[self.receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(#"didReceiveData...");
NSLog(#"Succeeded! Received %ld bytes of data",[data length]);
[self.receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"didFailWithError...");
NSLog(#"Connection failed! Error - %# %#",[error localizedDescription],[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
//lblError.text = [NSString stringWithFormat:#"Connection failed! Error - %#",[error localizedDescription]];
self.receivedData = nil;
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading...");
NSError *error = nil;
id result = [NSJSONSerialization JSONObjectWithData:self.receivedData options:kNilOptions error:&error];
if (error) {
NSLog(#"%#",error.localizedDescription);
NSLog(#"%#",[[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding]);
}else{
NSLog(#"Finished...Download/Parsing successful");
if ([result isKindOfClass:[NSArray class]])
NSLog(#"%#",result);
}
}
There was an error, and the log of error.localizesDescription was: "The data couldn’t be read because it has been corrupted". So, it appears that there is something wrong with what's coming back from the server which prevents the JSON parser from working correctly. I also printed out the string along with the error message. Maybe you can look at it carefully and try to figure out what's wrong with the data.
looking at your json you start with the array value (using square brackets) without a name. try reformatting you response with something like this:
{"results":[...the rest of your response..]}