passing a string var to a function - objective-c

When I run the code below
NSString *chemin;
chemin = [NSString stringWithFormat:#"chapitre0%d", [sender tag]];
NSLog(#"chemin : %#",chemin);
[detailChapitre loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:chemin ofType:#"html"]isDirectory:NO]]];
I got :
'NSInvalidArgumentException', reason: '* -[NSURL initFileURLWithPath:isDirectory:]: nil string parameter'
but *chemin is initialized to the right value in the log.
Certainly a noob question,
Thx for your help

This could be it, the chemin variable might have the correct chapter but the path might be wrong. So when you pass the wrong filepath to NSURL it would have returned null which inturn would have caused the crash.
First get the absolute path like so -
NSString *path = [[NSBundle mainBundle] pathForResource:#"chapter1" ofType:#"html"];

try initializing chemin and then release it. like this:
NSString *chemin;
chemin = [[NSString alloc] initWithFormat:#"chapitre0%d", [sender tag]];
NSLog(#"chemin : %#",chemin);
[detailChapitre loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:chemin ofType:#"html"]isDirectory:NO]]];
[chemin release];

This would seem to indicate that the file "chapitre0[whatever].html" is not where you expect it to be. This could be because an incorrect string is being constructed, but it could also just mean your build process isn't sticking the file in the right place or something like that. Look at the string indicated in your NSLog and then look in your built apps's Resources directory to confirm that the file is indeed there and named correctly.

Related

Saved image does not appear in file directory

I'm using the following code below save an image locally. It works without any errors, and I can preview the incoming image. The only problem is that the image never seems to actually be saved or appear in the Images directory. I use iExplorer to double check, and I have refreshed the folder and the image is still not there. Your thoughts are appreciated.
// I can preview this UIImage and it appears as expected
UIImage *image = [UIImage imageWithData:responseObject]; //responseImage is an image from online
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *docs = [paths objectAtIndex:0];
NSString* path = [docs stringByAppendingFormat:#"/Images/image1.jpg"];
NSData* imageData = [NSData dataWithData:UIImageJPEGRepresentation(image, .8)];
NSError *writeError = nil;
if(![imageData writeToFile:path options:NSDataWritingAtomic error:&writeError]) {
//This never fires, so you would think the image would have saved, but that does not appear to be the case!
NSLog(#"%#: Error saving image: %#", [self class], [writeError localizedDescription]);
}
I did also check to see if the file exists programmatically and apparently it does exist. However, when I try to reference it within a UIWebview, it doesn't load anything for that image.
Remember that NSFileManagers use NSString paths to read/write files, however UIWebViews use NSURLs. In order for you to load the file into a UIWebView, you'll need to convert your NSString path into an NSURL file URL.
So instead of something that looks like:
/Documents/Path/To/File.png
It needs to be
file:///Documents/Path/To/File.png
I believe the correct way to do this is to use the [NSURL fileURLWithPath:] method.
So it would look something like this:
NSFileManager* fileManager = [NSFileManager defaultManager];
NSString* path; //However you got your path here
if([fileManager fileExistsAtPath:path])
{
NSURL* fileURL = [NSURL fileURLWithPath:path];
NSURLRequest* request = [NSURLRequest requestWithURL: fileURL];
[_myWebView loadRequest:request];
}
This is too long to post as a comment, so I'm posting it as an answer.
I'm not sure about your if statement there. It does return a BOOL NO if the file operation fails, but I'm not exactly sure what "the operation fails" means. Just because the file is not written out does not necessarily mean that the operation failed. So it's better to check the NSError itself.
Instead of checking ![writeToFile], run the line without the if statement, and then check if(writeError != nil). If the if statement is true, then something went wrong, and if so, you can check the localized description of the error.
So to recap,
NSError* writeError = nil;
[imageData writeToFile:path options:NSDataWritingAtomic error:&writeError];
if(writeError != nil)
{
//Something went wrong
NSLog("File write error: %#", writeError.localizedDescription);
}

NSBundle crash when setting string name as number?

I am trying to play some sound, that its name is a number . so i create an NSString as number, and when i try to set it to the NSBundle, it is Null!
It does work with a word, such as #"yes" , as the name parameter
//name parameter only works as a string in words. when its a number it doesn't.
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:name ofType:type];
NSLog(#"%#",name); //logs 16 !
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath]; //crash!
the crash is because the soundFilePath is nil .
NSString *number=[NSString stringWithFormat:#"%d",16];
Ok. Problem is that i had to add the sounds into the build phase-copy bundle resources, so he can find them.

stringByReplacingOccurrencesOfString not working?

The first NSLog returns the correct URL After that I get this error.
2013-07-06 21:07:56.622 Social App[69682:14003] -[NSURL stringByReplacingOccurrencesOfString:withString:]: unrecognized selector sent to instance 0x9a4ae10
videoURL = [[tableData objectAtIndex:indexPath.row] objectForKey:#"streamURL"];
NSLog(#"URL; %#", videoURL);
videoURL = [videoURL stringByReplacingOccurrencesOfString:#"http://www.youtube.com/watch?v=" withString:#""];
videoURL = [videoURL stringByReplacingOccurrencesOfString:#"&feature=youtube_gdata_player" withString:#""];
NSLog(#"URL; %#", videoURL);
Any help is greatly appreciated.
On the third line it seems you are sending a NSString message to a NSURL. That is why the second NSLog says [NSURL stringBy...] and unrecognized selector, since the NSURL class does not have a method named stringBy....
What you have to do is insert this line between the second and third lines:
NSString* videoString = [videoURL absoluteString];
And then substitute videoURL with videoString on the lines where you call stringBy....
Use videoURL.absoluteString.
Right now you are trying to use a NSString method ( stringByReplacingOccurrencesOfString ) on a NSURL, that of course won't work. absoluteString will get you a NSString to work with.
videoURL is a NSURL
use:
stringUrl = [videoURL absoluteString];
then use stringurl for further operations like stringByReplacingOccurrencesOfString

NSURL is null in Simulator, but okay on iPad

I'm trying to load an audio file into AVAudioPlayer on the iPad. When I run it on the iPad it finds it in the bundle fine. However, if I try and run it through the simulator, I get a null error for NSURL. Here's the snippet of code (num is an arbitrary int):
NSString *name = [NSString stringWithFormat:#"st-answermachine-%i", num];
NSLog(#"name = %#", name);
NSString *path = [[NSBundle mainBundle] pathForResource:name ofType:#"m4a"];
NSLog(#"path = %#", path);
NSURL *url = [NSURL URLWithString:path];
NSLog(#"url = %#", url);
In the simluator, the Debugger Console traces this:
name = st-answermachine-1
path = /Users/joe/Library/Application Support/iPhone Simulator/3.2/Applications/B85E9CC8-6E39-47B9-XXXX-1E3A2CE145D1/MyApp.app/st-answermachine-1.m4a
url = (null)
But if I try it on the device, I get this:
name = st-answermachine-1
path = /var/mobile/Applications/116DA1CB-EA13-4B80-XXXX-EBD46C8E2095/MyApp.app/st-answermachine-1.m4a
url = /var/mobile/Applications/116DA1CB-EA13-4B80-XXXX-EBD46C8E2095/MyApp.app/st-answermachine-1.m4a
Any ideas why I might have this problem please?
Thanks!
URLWithString: expects a string containing an actual URL as its parameter (e.g. 'http://blah/' or 'file:///blah'). URLs can't contain spaces (as the simulator's path does), and that's why it's failing.
As Evan suggests, you need to use fileURLWithPath: to convert a path string to a URL object.

How to download file from particular url?

NSURL * url = #"http://192.168.100.161/UploadWhiteB/wh.txt";
NSData * data = [NSData dataWithContentsOfURL:url];
if (data != nil) {
NSLog(#"\nis not nil");
NSString *readdata = [[NSString alloc] initWithContentsOfURL:(NSData *)data ];
I write this code to download a file from given url... but i get an error on line
NSData * data = [NSData dataWithContentsOfURL:url];
uncaught exception...
so please help me out.
Your first line should be
NSURL * url = [NSURL URLWithString:#"http://192.168.100.161/UploadWhiteB/wh.txt"];
(NSURL is not a string, but can easily be constructed from one.)
I'd expect you to get a compiler warning on your first line--ignoring compiler warnings is bad. The second line fails because dataWithContentsOfURL: expects to be given a pointer to an NSURL object and while you're passing it a pointer that you've typed NSURL*, url is actually pointing to an NSString object.
NSString *file = #"http://192.168.100.161/UploadWhiteB/wh.txt";
NSURL *fileURL = [NSURL URLWithString:file];
NSLog(#"qqqqq.....%#",fileURL);
NSData *fileData = [[NSData alloc] initWithContentsOfURL:fileURL];
-[NSString initWithContentsOfURL:] is deprecated. You should be using -[NSString (id)initWithContentsOfURL:encoding:error:]. In either case, the URL paramter is an NSURL instance, not an NSData instance. Of course you get an error trying to initialize a string with the wrong type. You can initialize the string with the URL data using -[NSString initWithData:encoding:], or just initialize the string directly from the URL.