Converting URLWithString to NSURLConnection - json

I am new to iOS development and I am trying to retrieve some data from server.
I have used:
NSData *jsonDataString = [[NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error: nil] dataUsingEncoding:NSUTF8StringEncoding];
which is freezing my app's UI. I put it dispatch but this causes other issues.
How to convert this one to NSRULConnection which will reply NSData like URLWithString?
Thank you

I found the solution. I was dispatching [self function1[self function2[self function3]]]; where the function3 was the json request. After dispatching only function3 the result was fine

Related

How to play an audio file from JSON output?

I have an iOS app that outputs JSON information(from a mySQL database) in the form of a UITableView. This includes audio, images and text. While I can call the images and text, I am having trouble calling the audio (This is stored as a URL in the mySQL database) for example, this is the JSON output for the path to my audio file:
[{"audiopath = "http://my-website.com/audio/5552643-audio.caf"}]
This is the code I use to call the images and text but the audio isn't working. I have tried logging the path but it just comes up as NULL.
NSDictionary *words = [self.wordsArray objectAtIndex:index];
label.text = [words objectForKey:#"new"];
NSDictionary *images = [self.thumbArray objectAtIndex:index];
[imgView setImageWithURL:[NSURL URLWithString:[images objectForKey:#"thumbnail"]]];
NSDictionary *audio = [self.audioArray objectAtIndex:index];
NSURL *path = [NSURL URLWithString:[audio objectForKey:#"audiopath"]];
_audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:path error:nil];
NSLog(#"PATH:%#", path);
The error I am getting is:
'NSInvalidArgumentException', reason: '*** -[NSURL initFileURLWithPath:]: nil string parameter'
The audio is stored on my server so it is not included in the app bundle.. does that mean I need to download the file into my app? or is there another way? Anyone know what I am doing wrong? Any help appreciated.
I have figured it out. This is how I can target the image path:
NSURL *url = [NSURL URLWithString:[_wordDetail objectForKey:#"audiopath"]];
NSData *soundData = [NSData dataWithContentsOfURL:url];
audioPlayer = [[AVAudioPlayer alloc] initWithData:soundData error:NULL];
audioPlayer.delegate = self;
[audioPlayer play];

Parsing JSON which contains html data

I want to parse json data which contains html but there is a problem
I made a parser with this lines but always I got this error: The operation couldn’t be completed. (Cocoa error 3840.)
NSString *str = [[NSString alloc] initWithData:responseObject encoding:NSASCIIStringEncoding];
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding]
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:dataoptions:NSJSONReadingMutableContainers error:&error];
You need to fix the incoming JSON object. You will need to encode that HTML in your web-service (whatever that may be). You should be able to see the issue when you run your JSON through a validator like JSONViewer or JSONLint.

How to get the image from the base64encodedstring ?

I am using base64encoding for sending an UIImage to the server and then on the other end i am getting it back, converting the base64encodedstring in to NSData then trying to get my image back on an UIImageView.
Everything working fine sending the Base64encodedString and receiving it but when i am converting the NSData back in to UIImage it is throwing the following exception
-[__NSArrayI dataUsingEncoding:allowLossyConversion:] exception is comming with Base64 encoding
this is the code i am using for posting the image:
img=mainImage.image;
NSData *imgdata=UIImagePNGRepresentation(img);
NSString *imgstring=[imgdata base64EncodedString];
NSString *post =[[NSString alloc] initWithFormat:#"gid=%#&image=%#",[lblgid text],imgstring];
NSLog(#"PostData: %#",post);
NSURL *url=[NSURL URLWithString:#"http://www.abcd/updategameimage.php"];
And following is the code at receiving end
NSString *imgStr=[abc valueForKey:#"image"];
NSLog(#"%#",imgStr);
NSData *imgdata=[NSData dataWithBase64EncodedString:imgStr];
imge = [UIImage imageWithData:imgdata];
[imgview setImage:imge];
Here abc is NSMutableArray
Are you sure abc is a mutableArray?
Because you are sending it a valueForKey: method. This is a KVC method implemented by NSObject and it doesn't make sense to send it this message.
If you meant to send it the objectForKey: method instead - then that would be a message that you send to dictionaries, not arrays.
And, the error that you are getting:
-[__NSArrayI dataUsingEncoding:allowLossyConversion:] exception is comming with Base64 encoding
is telling you that an NSArray does not respond to dataUsingEncoding:allowsLossyConversion: messages - which is a method for NSString objects.
I think you are getting confused with your object types and need to get a better handle on what is what.

objective-c: creating a server method

Currently I am able to retrieve data from a MySQL db by using HTTP GET and an NSURL connection, but I need to know how to encapsulate this action into a method. Could somebody inform me of how to put the following code into a method so that I can call it throughout my app, and also so that I can show a UIActivityIndicator while the process is underway?
//somethign like this?
-(void)getDataFromServer:(NSString *)url{
//enter code here
}
My current server request: I am using this in didselectrowforindexpath, so that the following stuff is done whenever somebody selects a cell. The issue is that I keep re-using this same code in several different methods, so I assume that it is bad practice to keep copying/pasting this code rather than having a method.
// retrieve data
NSString *buildURL = [[NSString alloc] initWithFormat:#"http://myurl.com"];
// begin query
NSURL *url = [NSURL URLWithString:buildURL];
NSError *e;
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&e];
NSLog(#"jsonreturn: %#",jsonreturn);
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
EDIT:
Much better way to do this, which I just implemented, is to use ASIHTTPRequest. The library provides for all the needs which I was trying to accomplish with the method above.
Just take your whole second code block and put it inside the {} of the first code block. You probably want to return that jsonData variable instead of void, though.

ios5 - JSON Parsing - dictionary OK, not parsing to array

I am using the new ios5 "NSJSONSerialization" function to obtain some tech-news from a website. I seem to have everything working OK, up until the point when I try to parse the NSDictionary into an NSArray. I have included the code here. The first console test (test 1) is working great - I get a console full of returned json data. But at the second console test (test 2 - the one that checks the contents of the nsarray), gives this message: "Array returned: (null)". Any ideas? Is it because I reused the error variable, maybe? I'm stumped.
Here's the code:
// create the string for making the api call to the website
NSString* theURL = [NSString stringWithFormat:#"http://pipes.yahoo.com/pipes/pipe.run?_id=9DfJELfJ2xGnjAQWJphxuA&_render=json"];
// declare and assign variables necessary to generate the actual url request
NSError* err = nil;
NSURLResponse* response = nil;
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
NSURL* URL = [NSURL URLWithString:theURL];
[request setURL:URL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:30];
// make the actual url request - get the data from yahoo pipes, in json format
NSData* jsonData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
// assign the entire result to a dictionary
NSDictionary *resultsDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&err];
//*** test 1: use the console to test results:
NSLog(#"NSDictionary returned: %#",resultsDictionary);
// parse the whole returned list of items (in dictionary form) into a large array
NSArray* arrayOfReturnedItems = [resultsDictionary objectForKey:#"items"];
//*** test 2: view the items returned (in the console)
NSLog(#"Array returned: %#",[arrayOfReturnedItems objectAtIndex:0]);