Hpple implementation/Unrecognized selector - objective-c

I am working with the hpple html parser here: https://github.com/topfunky/hpple
To test the function I've added it to a simple project and am able to compile and open the simulator without errors, but when it is called, I get an unrecognized selector error.
//THIS ACTION SET TO RUN WITH THE PUSH OF A BUTTON
- (IBAction)parseElements{
NSString *urlRequest = item.link;
NSLog(#"urlRequest defined.");
NSData *htmlData = [NSString stringWithContentsOfURL:[NSURL URLWithString: urlRequest] encoding:NSUTF8StringEncoding error:nil];
NSLog(#"htmlData created.");
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
NSLog(#"xpathParser made.");
NSString *queriedItem = #"[#class='title']";
// THE APP FAILS WHILE TRYING TO EXECUTE THE NEXT LINE
NSArray *elements = [xpathParser searchWithXPathQuery:queriedItem];
NSLog(#"elements searched.");
TFHppleElement *element = [elements objectAtIndex:0];
NSLog(#"element recalled.");
NSString *storyTitle = [element content];
NSLog(#"The title of the story is: %#", storyTitle);
}
The NSLogs manage to display through "xpathParser made" and then I receive this unrecognized selector message:
-[__NSCFString bytes]: unrecognized selector sent to instance 0x6a52d60
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString bytes]: unrecognized selector sent to instance 0x6a52d60'
* First throw call stack:
(0x16c8052 0x1859d0a 0x16c9ced 0x162ef00 0x162ece2 0x495c 0x352e 0x2e3f 0x16c9ec9 0x1395c2 0x13955a 0x1deb76 0x1df03f 0x1de2fe 0x15ea30 0x15ec56 0x145384 0x138aa9 0x15b2fa9 0x169c1c5 0x1601022 0x15ff90a 0x15fedb4 0x15feccb 0x15b1879 0x15b193e 0x136a9b 0x2658 0x25b5)
terminate called throwing an exception
I understand it doesn't like SOMETHING, but what is causing the glitch or are additional frameworks/imports necessary for proper execution? As it stands I have UIKit, viewcontroller.h and TFHpple.h set as the only imports in that file.

Here's your problem:
NSData *htmlData = [NSString stringWithContentsOfURL:[NSURL URLWithString: urlRequest] encoding:NSUTF8StringEncoding error:nil];
TFHpple *xpathParser = [[TFHpple alloc] initWithHTMLData:htmlData];
TFHpple's initWithHTMLData is supposed to take an NSData. You declare htmlData to be an NSData, but the actual object you're assigning to it is an NSString.
This should fix it:
NSData *htmlData = [NSData dataWithContentsOfURL:[NSURL URLWithString: urlRequest]];

Related

Error Thread 1: signal SIGBRT

I'm learning Objective C and I'm following examples from this book. However in some examples I keep getting this error! I followed the steps exactly, please help! I've already tried restoring the iOS simulator to its default settings and still no luck.
It's an app where you can record a sound and play it back. Here's the code...
- (IBAction)recordAudio:(id)sender {
if ([self.recordButton.titleLabel.text isEqualToString:#"Record Audio"]){
[self.audioRecorder record];
[self.recordButton setTitle:#"Stop Recording"
forState:UIControlStateNormal];
} else {
[self.audioRecorder stop];
[self.recordButton setTitle:#"Record Audio"
forState:UIControlStateNormal];
// Load the new sound in the audioplayer for playback
NSURL *soundFileURL = [NSURL fileURLWithPath:[NSTemporaryDirectory()
stringsByAppendingPaths:#"sound.caf"]];
self.audioPlayer = [[AVAudioPlayer alloc]
initWithContentsOfURL:soundFileURL error:nil];
}
}
I ran part of your code, and this was the error message:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '***
-[__NSCFString stringsByAppendingPaths:]: paths argument is not an array'
As the documentation says, stringsByAppendingPaths returns an NSArray of NSString objects made by separately appending each NSString in an NSArray of paths to the receiver. #"sound.caf" is an NSString, not an NSArray, which raises the exception.
Change the following:
NSURL *soundFileURL = [NSURL fileURLWithPath:[NSTemporaryDirectory()
stringsByAppendingPaths:#"sound.caf"]];
To:
NSURL *soundFileURL = [NSURL fileURLWithPath:[NSTemporaryDirectory()
stringByAppendingPathComponent:#"sound.caf"]];
and it should work.

Error in NSMutableArray

I am very new to ios development, I am trying to add some values from NSMutableDictionary to NSMutableArray, when I run the code I get this error
2012-05-29 14:09:34.913 iShop[7464:f803] -[__NSCFArray objectForKey:]:
unrecognized selector sent to instance 0x6e423d0 2012-05-29
14:09:34.915 iShop[7464:f803] * Terminating app due to uncaught
exception 'NSInvalidArgumentException', reason: '-[__NSCFArray
objectForKey:]: unrecognized selector sent to instance 0x6e423d0'
* First throw call stack: (0x13cb022 0x155ccd6 0x13cccbd 0x1331ed0 0x1331cb2 0x2bb7 0x13cce42 0x93b9df 0x139f94f 0x1302b43 0x1302424
0x1301d84 0x1301c9b 0x12b47d8 0x12b488a 0x15626 0x28bd 0x2825)
terminate called throwing an exception(lldb)
below is my code:
-(void) getData:(NSData *) response {
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
//NSLog(#"%#", json);
jsonArray = [[NSMutableArray alloc] init];
jsonArray = [json objectForKey:#"Name"];
NSLog(#"%#", jsonArray);
}
- (void)viewDidLoad {
[super viewDidLoad];
jsonURL = [NSURL URLWithString:#"http://localhost:8888/read_product_list.php"];
dispatch_async(BgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:jsonURL];
[self performSelectorOnMainThread:#selector(getData:)
withObject:data waitUntilDone:YES];
});
}
JSONObjectWithData return an object of type id. depending on the structure of your received json data.
The data recieved is eiher NSDictionary or NSArray. In your case I am guessing the top level object is of type NSArray which does not respond to objectForKey

App crash after '

My application is crashing when a ' appears in the title of the JSON code i'm parsing.
This line is loading the title's:
[[cell textLabel] setText:[item objectForKey:#"title"]];
JSON:
NSString *jsonString = [NSString
stringWithContentsOfURL:[NSURL URLWithString:#"**test.php"]
encoding:NSStringEncodingConversionAllowLossy
error:nil];
// Create parser
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *results = [parser objectWithString:jsonString error:nil];
parser = nil;
// Set tableData
[self setTableData:[results objectForKey:#"items"]];
Crash:
tableData NSArray * 0x00000001
2012-04-10 10:29:11.446 *[21222:f803] -[NSNull isEqualToString:]:
unrecognized selector sent to instance 0x146ace8 2012-04-10
10:29:11.447 *[21222:f803] * Terminating app due to uncaught
exception 'NSInvalidArgumentException', reason: '-[NSNull
isEqualToString:]: unrecognized selector sent to instance 0x146ace8'
* First throw call stack: (0x13d4022 0x1565cd6 0x13d5cbd 0x133aed0 0x133acb2 0x15e0ff 0x2b10 0xb8c54 0xb93ce 0xa4cbd 0xb36f1 0x5cd21
0x13d5e42 0x1d8c679 0x1d96579 0x1d1b4f7 0x1d1d3f6 0x1db81ce 0x1db8003
0x13a8936 0x13a83d7 0x130b790 0x130ad84 0x130ac9b 0x12bd7d8 0x12bd88a
0x1e626 0x1ded 0x1d55) terminate called throwing an exception(lldb)
The key part of that crash info is: unrecognized selector sent to instance ... [NSNull isEqualToString:]
It looks like your JSON contains null somewhere that you are expecting a string. Later on, probably inside of setTableData: you will be doing something like this:
NSString* whatever = [items objectForKey:#"whatever"];
if([whatever isEqualToString:#"hello"]){
...
}
And that will crash, because the whatever variable contains NSNull, not an NSString like you were expecting.

Converting NSMutableString to NSUrl in Objective C

I actually stuck with a problem while parsing xml-file from a dynamic url in Objective-C.
The Parser works fine for the whole project, but now I have to set a dynamic URL to parse the needed XML-File.
I have two Variables: One for the BaseURL and one for the Params.
Here is my documented Code:
//The Baseurl
NSMutableString* baselink = [NSMutableString stringWithString:zimmertyp.typlink];
//Adds the params to URL
[baselink appendString:aSlice.link];
//In Log it shows the right url to my XML-File with params
NSLog(#"Selected-URL: %#", url);
//I tried to convert the String to NSURL here
NSURL *url = [NSURL URLWithString: baselink];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithContentsOfURL:url];
self.navigationItem.prompt = #" ";
//Initialize the delegate.
XMLParser *parser = [[XMLParser alloc] initXMLParser];
//Set delegate
[xmlParser setDelegate:parser];
//Start parsing the XML file.
BOOL success = [xmlParser parse];
if(success)
NSLog(#"No Errors");
else
NSLog(#"Error Error Error!!!");
Everytime the Parser tries to walk through, I get:
2011-02-16 16:40:03.371 Project[15566:207] Selected-URL: http://xml.projectwebsite.de/price/doppelzimmer.xml
?Zimmertyp=Doppelzimmer+Classic
2011-02-16 16:40:03.373 Project[15566:207] Error Error Error!!!
2011-02-16 16:40:03.374 Project[15566:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSCFString stringByAppendingString:]: nil argument'
It seems like the NSUrl is empty, or am I wrong?
The App crashes right at the point when the Parser initialized with the url.
Can anyone tell me what's my fault?
greeting,
Zarakas
I solved the problem by myself. The AppendString method added whitespaces to the String... dunno why. I escaped the spaces from the string. Now parser works fine.. ;)

"Terminating app due to uncaught exception 'NSInvalidArgumentException'" error with stringByTrimmingCharactersInSet on iPhone

I am reading JSON data back from a server, and I am trying to parse a particular string that contains an HTML URL. The data is in an NSString called current_weatherIconUrl2. The console output from Xcode is below:
2010-07-06 17:17:46.628 WhatToDo[13437:20b] Current Condition: URL2:("http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png")
What I tried to do is use "stringByTrimmingCharactersInSet" to parse the '(', '"', and also the line feed and newlines, but I am instead getting the NSInvalidArgumentException:
2010-06-30 00:18:07.357 WhatToDo[7299:20b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSCFArray stringByTrimmingCharactersInSet:]: unrecognized selector sent to instance 0x3e84970'
Here is an extract of the data that is returned from the server (information I want to extract is bolded):
2010-07-06 17:17:46.627 WhatToDo[13437:20b] Results: {
data = {
"current_condition" = (
{
cloudcover = 75;
humidity = 42;
"observation_time" = "08:47 AM";
precipMM = "0.0";
pressure = 1003;
"temp_C" = 36;
"temp_F" = 97;
visibility = 10;
weatherCode = 113;
weatherDesc = (
{
value = Sunny;
}
);
**weatherIconUrl = (
{
value = "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0001_sunny.png";
}
);**
winddir16Point = WSW;
winddirDegree = 250;
windspeedKmph = 31;
windspeedMiles = 19;
}
);
};
}
Here is the code that parses the data into NSString variables.
- (void) readWeather {
NSLog(#"readWeather started");
NSMutableArray *imageArray = [[NSMutableArray alloc] init];
NSData *jsonObjectString;
NSString *completeString = [NSString stringWithFormat:
#"http://www.worldweatheronline.com/feed/weather.ashx?key=988ae47cc3062016100606&lat=25.04&lon=121.55&num_of_days=5&format=json", jsonObjectString];
NSLog(#"Weather URL: %#", completeString);
NSURL *urlForValidation = [NSURL URLWithString:completeString];
NSMutableURLRequest *validationRequest = [[NSMutableURLRequest alloc] initWithURL:urlForValidation];
[validationRequest setHTTPMethod:#"POST"];
NSData *responseData = [NSURLConnection sendSynchronousRequest:validationRequest returningResponse:nil error:nil];
[validationRequest release];
// Store incoming data into a string
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// Create a dictionary from the JSON string
NSDictionary *results = [jsonString JSONValue];
NSLog(#"Results: %#", results);
NSArray *data = [[results objectForKey:#"data"] objectForKey:#"current_condition"];
NSArray *data2 = [[results objectForKey:#"data"] objectForKey:#"weather"];
NSCharacterSet *skipSet = [NSCharacterSet characterSetWithCharactersInString:#"("];
for (NSArray *current_condition in data)
{
// Get title of the image
NSString *temp_C = [current_condition valueForKey:#"temp_C"];
NSString *current_weatherDesc = [current_condition valueForKey:#"weatherDesc"];
NSString *current_weatherIconUrl = [current_condition valueForKey:#"weatherIconUrl"];
NSString *current_weatherIconUrl2= [current_weatherIconUrl valueForKey:#"value"];
//Commented out because this will create an exception:
//NSString *current_weatherIconUrl3 = [current_weatherIconUrl2 stringByTrimmingCharactersInSet:skipSet];
//NSLog(#"Current Condition: URL2: %#", *(current_weatherIconUrl3);
//Commented out because this will create an exception:
//current_weatherIconUrl3 = [current_weatherIconUrl3 stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
}
Can someone tell me what I am doing wrong or if there is a better method than using stringByTrimmingCharactersInSet?
The error you're getting actually describes what goes wrong:
2010-06-30 00:18:07.357 WhatToDo[7299:20b] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[NSCFArray stringByTrimmingCharactersInSet:]: unrecognized selector sent to instance 0x3e84970'
You're trying to send an unrecognized selector (stringByTrimmingCharactersInSet:) to an instance of NSCFArray (NSArray).
Obviously, this selector only exists on NSString, so this won't work.
It appears that [current_weatherIconUrl valueForKey:#"value"] really is an NSArray, not an NSString.
Thanks for your help Douwe M. I was able to make some modifications, and now the code creates the variables I need. See below...
NSArray *weatherIconUrl2= [weatherIconUrl valueForKey:#"value"];
NSString *weatherIconUrl3 = [[weatherIconUrl2 valueForKey:#"description"] componentsJoinedByString:#""];
[imageArray addObject:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:weatherIconUrl3]]]];
-Todd
Your json response may not in a correct format.
So, please validate your JSON response on jsonlint