【问题标题】:URLWithString returns nil for resource path - iphoneURLWithString 为资源路径返回 nil - iphone
【发布时间】:2011-01-07 22:45:36
【问题描述】:

由于某种原因在获取资源的 URL 时出现问题:此代码在 viewDidLoad 中,它在其他应用程序中也可以使用,但由于某种原因不在此处:

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

日志输出:

音频字符串:/var/mobile/Applications/D9FA0569-45FF-4287-8448-7EA21E92EADC/SoundApp.app/sound.wav

音频网址:0

Error Error Domain=NSOSStatusErrorDomain Code=-50 "无法完成操作。(OSStatus error -50.)"

【问题讨论】:

    标签: iphone resources nsurl


    【解决方案1】:

    您没有足够仔细地阅读响应 - 您正在使用 URLWithString,而您应该使用 fileURLWithPath。您不能将 file:// 路径传递给 URLWithString。我认为您还需要在字符串前面添加 file://,因为您只有一个路径(正如所指出的没有协议)。

    【讨论】:

      【解决方案2】:

      只需将一行改为:

          NSURL* audioURL = [NSURL fileURLWithPath:audioString];
      

      【讨论】:

        【解决方案3】:

        您的字符串没有协议,因此它是无效的url。试试这个...

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

        【讨论】:

        • 对不起,我缩写了日志条目,但字符串是有效路径,使用扩展路径没有区别
        • 对不起,我应该更仔细地阅读这篇文章。更改为 fileURLWithPath 确实解决了问题。谢谢!
        【解决方案4】:

        您在NSLog 方法中将audioURL 传递为%d,因此您得到0。如果您将它作为%@ 的对象传递,您将得到NULL

        尝试像这样传递到音频播放器并跳过字符串。

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

        【讨论】:

        • 我原来的调用是 [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:[[NSBundle mainBundle] pathForResource:@"sound" ofType:@"wav"]] error:nil];但我仍然有同样的问题;我只是将其拆分以便于调试
        猜你喜欢
        • 2015-07-30
        • 1970-01-01
        • 1970-01-01
        • 2013-01-13
        • 2013-12-04
        • 2010-12-31
        • 1970-01-01
        • 2019-11-24
        • 1970-01-01
        相关资源
        最近更新 更多