NSURL的两个初始化方法的区别:如果是网络请求的url,常用的遍历构造器方法是:URLWithString:
如果是使用本地的URL不要用这个方法,而要用 fileURLWithString:
今天做了一个音频播放器,代码如下
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
NSString *path = [[NSBundle mainBundle] pathForResource:@"wohenchou" ofType:@"mp3"];
NSURL *url1 = [[NSURL alloc] initFileURLWithPath:path];
NSURL *url2 = [NSURL URLWithString:path];
NSError *error = nil;
NSURL *url = [[NSBundle mainBundle] URLForResource:@"wohenchou" withExtension:@"mp3"];
self.avAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
打印出url1、url2和url的结果如下:
(lldb) po url1
file:///Users/lanou3g/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/C643C75D-01D1-414F-B017-39994F3FFEF6/TestAudio.app/wohenchou.mp3
(lldb) po url2
nil
(lldb) po url
file:///Users/lanou3g/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/C643C75D-01D1-414F-B017-39994F3FFEF6/TestAudio.app/wohenchou.mp3
(lldb)
所以使用URLWithString:得到的avAudioPlayer对象怎么都是nil。
还有这两个方法看似差不多
NSString *path3 = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSURL *url3 = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
结果却不一样
(lldb) po path3
/Users/lanou3g/Library/Application Support/iPhone Simulator/7.1/Applications/C643C75D-01D1-414F-B017-39994F3FFEF6/Documents
(lldb) po url3
file:///Users/lanou3g/Library/Application%20Support/iPhone%20Simulator/7.1/Applications/C643C75D-01D1-414F-B017-39994F3FFEF6/Documents/
(lldb)
如果想要找沙盒中的文件,用path3的路径来找,用url3找不到。