URLWithString returns nil for resource path - iphone

我怕爱的太早我们不能终老 提交于 2020-01-01 09:24:12

问题


Having a problem getting the URL for a resource for some reason: This code is in viewDidLoad, and it's worked in other applications, but not here for some reason:

NSString* audioString = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"wav"];
NSLog(@"AUDIO STRING: %@" , audioString);

NSURL* audioURL = [NSURL URLWithString:audioString];
NSLog(@"AUDIO URL: %d" , audioURL);

NSError* playererror;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:audioURL error:&playererror];
[audioPlayer prepareToPlay];    

NSLog(@"Error %@", playererror);

LOG OUTPUT:

AUDIO STRING: /var/mobile/Applications/D9FA0569-45FF-4287-8448-7EA21E92EADC/SoundApp.app/sound.wav

AUDIO URL: 0

Error Error Domain=NSOSStatusErrorDomain Code=-50 "Operation could not be completed. (OSStatus error -50.)"


回答1:


Your string has no protocol, so it's an invalid url. Try this...

NSString* expandedPath = [audioString stringByExpandingTildeInPath];
NSURL* audioUrl = [NSURL fileURLWithPath:expandedPath];



回答2:


Just change one line to this:

    NSURL* audioURL = [NSURL fileURLWithPath:audioString];



回答3:


You're passing audioURL in your NSLog method as %d hence why you get 0. If you pass it as an object with %@ you'll get NULL.

Try passing into the audioplayer like this and skip the string.

NSURL *fileURL = [[NSURL alloc] initFileURLWithPath: [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"wav"]];



回答4:


You aren't reading the responses carefully enough - you are using URLWithString, when you should use fileURLWithPath. You can't pass a file:// path to URLWithString. I think you also need to prepend file:// at the front of the string as you have only a path (which as pointed out has no protocol).



来源:https://stackoverflow.com/questions/2112927/urlwithstring-returns-nil-for-resource-path-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!