I have set up a simple Objective-C class in my iOS app which has one simple task, to download a JSON file, parse it and then pass back a NSString which contains a variable parsed from the downloaded JSON file.
The problem I have is that I am calling this class from another class and this all works great however I need to pass back the NSString to the class from which I am calling it from.
The problem is that the method passes back the empty NSString BEFORE connectionDidFinishLoading happens.... And so the NSString never gets assigned a string......
I have setup a while loop in my method but it doesn't really work.....
here is my code:
-(NSString *)get_user_icon:(NSString *)YT_ID {
// Set BOOL to 0 for initial setup.
icon_check = 0;
NSString *url_YT = [NSString stringWithFormat:YOUT_profile_part_2, YT_ID];
dispatch_queue_t downloadQueue = dispatch_queue_create("Icon downloader YouTube", NULL);
dispatch_async(downloadQueue, ^{
dispatch_async(dispatch_get_main_queue(), ^{
NSURLRequest *theRequest_YT = [NSURLRequest requestWithURL:[NSURL URLWithString:url_YT]];
NSURLConnection *theConnection_YT = [[NSURLConnection alloc] initWithRequest:theRequest_YT delegate:self];
if (theConnection_YT) {
YT_JSON_FEED = [[NSMutableData alloc] init];
NSLog(#"Respoce happening...");
}
else {
NSLog(#"failed");
}
});
});
while (icon_check == 0) {
NSLog(#"Wait");
}
return icon_url;
}
/// Data loading ///
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[YT_JSON_FEED setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[YT_JSON_FEED appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSString *msg = [NSString stringWithFormat:#"Failed: %#", [error description]];
NSLog(#"%#",msg);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *myError = nil;
NSDictionary *feed = [NSJSONSerialization JSONObjectWithData:YT_JSON_FEED options:NSJSONReadingMutableLeaves error:&myError];
icon_url = [[[[[feed objectForKey:#"items"] valueForKey:#"snippet"] valueForKey:#"thumbnails"] valueForKey:#"default"] valueForKey:#"url"];
icon_check = 1;
}
For a synchronous request (blocking until there is something to return), use NSURLConnection's sendSynchronousRequest:returningResponse:error: instead. Like so:
-(NSString *)get_user_icon:(NSString *)YT_ID {
NSString *url_YT = [NSString stringWithFormat:YOUT_profile_part_2, YT_ID];
NSURLRequest *theRequest_YT = [NSURLRequest requestWithURL:[NSURL URLWithString:url_YT]];
NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:theRequest_YT returningResponse:&response error:&error];
//Check response and error for possible errors here.
//If no errors.
NSDictionary *feed = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&myError];
icon_url = [[[[[feed objectForKey:#"items"] valueForKey:#"snippet"] valueForKey:#"thumbnails"] valueForKey:#"default"] valueForKey:#"url"];
return icon_url;
}
However this is not recommended. You need to change your API to be asynchronous. Either delegate-based, but more preferably, using block-based API.
Related
I want to download some items from my host,
but now I get a warning:
'connectionWithRequest:delegate:'is deprecated in iOS9.0 - Use NSURLSession'
I've searched everywhere, but unfortunately I couldn't find any solution.
Can you help me?
My code looks like this:
- (void)downloadItems
{
// Download the json file
NSURL *jsonFileUrl = [NSURL URLWithString:#"http://myhost.com/test.php"];
// Create the request
NSURLRequest *urlRequest = [[NSURLRequest alloc] initWithURL:jsonFileUrl];
// Create the NSURLConnection
[NSURLConnection connectionWithRequest:urlRequest delegate:self];
}
#pragma mark NSURLConnectionDataProtocol Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// Initialize the data object
_downloadedData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the newly downloaded data
[_downloadedData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// Create an array to store the locations
NSMutableArray *_locations = [[NSMutableArray alloc] init];
// Parse the JSON that came in
NSError *error;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:_downloadedData options:NSJSONReadingAllowFragments error:&error];
// Loop through Json objects, create question objects and add them to our questions array
for (int i = 0; i < jsonArray.count; i++)
{
NSDictionary *jsonElement = jsonArray[i];
// Create a new location object and set its props to JsonElement properties
Location *newLocation = [[Location alloc] init];
newLocation.idS = jsonElement[#"idStatistic"];
newLocation.temp = jsonElement[#"temp"];
newLocation.hum = jsonElement[#"hum"];
newLocation.date_time = jsonElement[#"date_time"];
// Add this question to the locations array
[_locations addObject:newLocation];
}
// Ready to notify delegate that data is ready and pass back items
if (self.delegate)
{
[self.delegate itemsDownloaded:_locations];
}
}
Replacing NSURLConnection line with:
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:jsonFileUrl
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
// handle response
}] resume];
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 am using a button action to update the value of a MySQL table field. The update is perform in the web server, but I need to update a UILabel text in my view Controller.
This is the code I have implemented:
- (IBAction)votarAction:(id)sender {
//URL definition where php file is hosted
dispatch_queue_t backgroundQueue = dispatch_queue_create("com.mycompany.myqueue", 0);
dispatch_async(backgroundQueue, ^{
int categoriaID = [[detalleDescription objectForKey:#"idEmpresa"] intValue];
NSString *string = [NSString stringWithFormat:#"%d", categoriaID];
NSLog(#"ID EMPRESA %#",string);
NSMutableString *ms = [[NSMutableString alloc] initWithString:#"http://mujercanariasigloxxi.appgestion.eu/app_php_files/cambiarvaloracionempresa.php?id="];
[ms appendString:string];
// URL request
NSLog(#"URL = %#",ms);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:ms]];
//URL connection to the internet
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self];
dispatch_async(dispatch_get_main_queue(), ^{
//update your label
});
});
}
#pragma NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
//buffer is the object Of NSMutableData and it is global,so declare it in .h file
buffer = [NSMutableData data];
NSLog(#"ESTOY EN didReceiveResponse*********");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"ESTOY EN didReceiveDATA*********");
[buffer appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Here You will get the whole data
NSLog(#"ESTOY EN didFINISHLOADING*********");
NSError *jsonParsingError = nil;
NSArray *array = [NSJSONSerialization JSONObjectWithData:buffer options:0 error:&jsonParsingError];
//And you can used this array
NSLog(#"ARRAY = %#",array);
//HERE LABEL.TEXT UPDATE CODE
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR de PARSING");
NSLog(#"ESTOY EN didFAILWITHERROR*********");
}
As I told you, the field value at the MySQL table is updated every time the button is tapped, but the problem is that the NSURLConnection delegate methods are never called.
Any help is welcome
In your view controller's header file add: <NSURLConnectionDelegate>
Also, there's no need to throw the NSURLConnection into a seperate background process, maybe that's why the delegates aren't called. NSURLConnection is already asynchronous
Perhaps try something like this:
- (IBAction)votarAction:(id)sender
{
int categoriaID = [[detalleDescription objectForKey:#"idEmpresa"] intValue];
NSString *originalString = [NSString stringWithFormat:#"%d", categoriaID];
NSMutableString *mutablesString = [[NSMutableString alloc] initWithString:#"http://mujercanariasigloxxi.appgestion.eu/app_php_files/cambiarvaloracionempresa.php?id="];
[mutableString appendString:originalString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:mutableString]];
request.cachePolicy = NSURLRequestReloadIgnoringLocalAndRemoteCacheData;
request.timeoutInterval = 5.0;
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError)
{
if (data)
{
NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
dispatch_async(dispatch_get_main_queue(), ^
{
// Update your label
self.label.text = [array objectAtIndex:someIndex];
});
}
else
{
// Tell user there's no internet or data failed
}
}];
}
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..]}