objective-c - NSURL 在模拟器中为空,但在 iPad 上没问题

标签 objective-c ipad ios nsurl ios-simulator

我正在尝试将音频文件加载到 iPad 上的 AVAudioPlayer 中。当我在 iPad 上运行它时,它发现它在包中很好。但是,如果我尝试通过模拟器运行它,我会收到 NSURL 的空错误。这是代码片段(num 是任意 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);

在模拟器中,调试器控制台跟踪这个:

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)

但如果我在设备上尝试,我会得到:

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

请问我为什么会遇到这个问题?

谢谢!

最佳答案

URLWithString: 需要一个包含实际 URL 的字符串作为其参数(例如“http://blah/”或“file:///blah”)。 URL 不能包含空格(就像模拟器的路径一样),这就是它失败的原因。

正如 Evan 所建议的,您需要使用 fileURLWithPath: 将路径字符串转换为 URL 对象。

关于objective-c - NSURL 在模拟器中为空,但在 iPad 上没问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4194636/

相关文章:

iphone - 使用 NSJSONSerializer iOS 发布 http JSON 请求

ios - 如何将UIView添加到iOS中的UIScrollView中(具有动态内容的View)

iphone - 从脚本将文件添加到 xcode 项目

ios - UIPickerController 使应用程序崩溃

iOS 简单的下拉数字选择器

objective-c - 新建、删除、Objective-C++ 和泄漏

ios - ScrollView 不适用于 iPad 但适用于 iPhone

ios - React Native ios不显示本地镜像

ios - 方向的 Swift 2 语法错误.Forward

ios - iOS App 中的自定义证书