URL as a string and values in Xcode - ios

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

Related

Parsing JSON in iOS application

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

how to update json file in ios during runtime from the server

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

objectFromJSONString in JSONKit.h returns null in iOS

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..]}

How to decode route points from the JSON Output Data?

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.

URL Connection ios

I want to create connection from my iphone to my website where I will be retrieving data that needs to be parsed. I am not having any luck so far and am kind of confused in regard to the following delegate methods:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
Are these methods called upon there own from my code or do I manually need to call them? Do I need to declare a delegate anywhere in my .h file?
This is what I have been doing but have had no luck. If anyone can explain it would be appreciated. It says my connection is successful made but the NSLog comes up in the console for didFailWithError.
Thanks
-(void) data: (id) sender
{
NSString *stringToBeSent;
NSURL *siteWithNumbers;
NSString *translation;
NSError *error;
NSString *boo;
sender= [sender lowercaseString];
sender= [sender stringByReplacingOccurrencesOfString:#"," withString:#""];
receivedData= [[NSMutableData alloc] init]; //declared in .h file as NSMutableData
stringToBeSent= [[NSString alloc]
initWithFormat:#"http://xxxx/sql.php? data=%#",sender];
NSURLRequest *theRequest=[NSURLRequest
requestWithURL:[NSURL URLWithString:stringToBeSent]];
NSURLConnection *conn= [[NSURLConnection alloc]
initWithRequest:theRequest delegate:self];
//[self createConnectionWithPath:stringToBeSent];
if(conn)
{
NSLog(#"Connection Successful");
}
else
{
NSLog(#"Connection could not be made");
}
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
/* appends the new data to the received data */
NSLog(#"here now1");
[self.receivedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
NSString *stringData= [[NSString alloc]
initWithData:receivedData encoding:NSUTF8StringEncoding];
NSLog(#"Got data? %#", stringData);
[conn release];
conn = nil;
}
- (void)connection:(NSURLConnection *)
connection didFailWithError:(NSError *)error
{
NSLog(#"fail");
}
//in .h file
#interface yourViewController : UIViewController<NSURLConnectionDelegate>
{
NSMutableData *responseData;
}
// in .m file
-(void) data: (id) sender
{
NSString *strWithURL = [NSString stringWithFormat:#"%#%#",TownsServiceURL,state];
strWithURL = [strWithURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"strConfirmChallenge=%#",strWithURL);
NSURL *myURL = [NSURL URLWithString:strWithURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:60];
[NSURLConnection connectionWithRequest:request delegate:self];
}
//Delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Connection failed with error: %#", [error localizedDescription]);
UIAlertView *ConnectionFailed = [[UIAlertView alloc]
initWithTitle:#"Connection Failed"
message: [NSString stringWithFormat:#"%#", [error localizedDescription]]
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[ConnectionFailed show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *s = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
}

Resources