Converting NSMutableString to NSUrl in Objective C - 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.. ;)

Related

Terminate called throwning an exception

I have make a piece of code for playing a video file. But when i build it i get the folowing error:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: ' -[NSURL initFileURLWithPath:]: nil string parameter'
First throw call stack:
(0x1ed8022 0x11c0cd6 0x1e80a48 0x1e809b9 0xc6553b 0xc654c5 0x2be8 0x1ed9e99 0x32614e 0x3260e6 0x3ccade 0x3ccfa7 0x3cc266 0x34b3c0 0x34b5e6 0x331dc4 0x325634 0x17baef5 0x1eac195 0x1e10ff2 0x1e0f8da 0x1e0ed84 0x1e0ec9b 0x17b97d8 0x17b988a 0x323626 0x29b2 0x2925)
terminate called throwing an exception
I have tried a lot to fix it but nothing does work! Do you no a solution? And yes, i have implementated the mediaplayer framework!
I have coded the follwing code:
-(IBAction)playvideo {
NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]
pathForResource:#"film" ofType:#"mp4"]];
MPMoviePlayerViewController *playercontroller = [[MPMoviePlayerViewController alloc]
initWithContentURL:url];
[self presentMoviePlayerViewControllerAnimated:playercontroller];
playercontroller.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
[playercontroller.moviePlayer play];
[playercontroller release];
playercontroller = nil;
}
The problem is described in this line:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: ' -[NSURL initFileURLWithPath:]: nil string parameter'
Which is telling you that you are passing a nil into a parameter that doesn't allow a nil.
Steps to be sure that this is the problem:
-(IBAction)playvideo {
NSString *videoPath = [[NSBundle mainBundle] pathForResource:#"film" ofType:#"mp4"]
if (!videoPath) {
NSLog(#"Video path is nil. My bundle must be set up incorrectly");
return; // return early.
}
NSURL *url = [NSURL fileURLWithPath:videoPath];
MPMoviePlayerViewController *playercontroller = [[MPMoviePlayerViewController alloc]
initWithContentURL:url];
// The rest of your implementation here.
}
This should at least help you to localise the problem.
As an aside - you should be using the URL based methods for getting resources instead of string based file-paths. But one thing at a time.

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.

Hpple implementation/Unrecognized selector

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

EXC_BAD_ACCESS on NSLog unless the NSString is manipulated and printed first

I'm trying to get a feel for objective C, so I wrote the code below to try to print the contents of a web page:
id url = [NSURL URLWithString:#"http://www.google.com"];
NSURLRequest* req = [NSURLRequest requestWithURL:url];
NSURLResponse* resp = [NSURLResponse new];
NSURLConnection* conn = [NSURLConnection new];
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:req returningResponse:&resp error:&error];
NSString* html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// printf([[html substringToIndex:50] cString]);
NSLog(html);
when I run this as-is, I get EXC_BAD_ACCESS on the NSLog line. When I uncomment the second-last line it works. If I change the printf to an assignment it stops working again. I'm clearly missing something here about how the memory model works, but it seems like the commented out line shouldn't make any difference since it's creating a new string and it really seems like printf vs an assignment shouldn't make a difference. In the Xcode debugger when the program crashes I can see that html does contain the HTML string I wanted to print.
try NSLog(#"%#", html) instead of just NSLog (html)

NSXMLParser with UTF8 Data

I'm having a really hard time trying to figure this out and would really appreciate any help.
I'm trying to parse a utf 8 string with NSXMLParser but it won't work.
here is my string
<?xml version="1.0" encoding="UTF-8"?><host><type>mac</type><port>62181</port><address>192.168.1.159</address><hostname>Samuel’s%20Mac%20Book</hostname><username>samuelw</username></host>
and here the parsing code
- (void) parse:(NSString*)XMLEncodedString withLength:(int)l_length {
#ifndef NDEBUG
NSLog(#"Received lookup %#",XMLEncodedString);
#endif
NSData* data=[XMLEncodedString dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];
[parser setDelegate:self]; // The parser calls methods in this class
[parser setShouldProcessNamespaces:NO]; // We don't care about namespaces
[parser setShouldReportNamespacePrefixes:NO]; //
[parser setShouldResolveExternalEntities:NO]; // We just want data, no other stuff
[parser parse]; // Parse that data..
[parser release];
}
the XMLEncodedString is constructed like this
- (void) checkForReceive {
//NSLog(#"listener: waiting to recvfrom...\n");
addr_len = sizeof their_addr;
if ((numbytes = recvfrom(sockfd, buf, MAXBUFLEN-1 , 0,
(struct sockaddr *)&their_addr, &addr_len)) == -1) {
perror("recvfrom");
return;
}
buf[numbytes] = '\0';
NSString * string = [[NSString alloc] initWithUTF8String:buf];
[self parse:string withLength:numbytes];
[string release];
}
my problem is coming from the Unicode Character 'RIGHT SINGLE QUOTATION MARK' (U+2019) that I have in my string and I am getting this error:
2010-07-19 17:13:35.734 SwypeSendForMac2[34354:4233] Error Domain=NSXMLParserErrorDomain Code=73 "The operation couldn’t be completed. (NSXMLParserErrorDomain error 73.)"
2010-07-19 17:13:35.736 SwypeSendForMac2[34354:4233] Error Domain=NSXMLParserErrorDomain Code=76 "The operation couldn’t be completed. (NSXMLParserErrorDomain error 76.)"
In your connection method that calls the xml, try replacing any problem characters with something like this:
NSString *final = [connRespStr
stringByReplacingOccurrencesOfString:#"&" withString:#" and "];
The above line replaces all ampersands with and, maybe use this to replace the singe quotes?
Also, I believe 'error 76' has something to do with not closing an xml tag.
EDIT: Just realized how old this is, maybe the above info will be worthwhile to future searchers.