从本地NSURL转换NSData [英] Convert NSData from local NSURL

查看:632
本文介绍了从本地NSURL转换NSData的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用AVAudioPlayer类的声音播放器。我在另一个视图中下载了一些项目,并将其文件路径存储为NSURL,然后将NSURL传递给Player视图控制器。但是尝试传递对象时出现错误。

  ***由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'-[__ NSCFString path]:无法识别的选择器发送至实例0x1700c86c0'

这是代码:

  NSData * data = [NSData dataWithContentsOfFile:[podcastSource路径]]; 
NSError *错误;
mPlayer = [[AVAudioPlayer分配] initWithData:data error:& error];
[mPlayer setDelegate:self];

if(mPlayer == nil)
{
NSLog(@%@,error);
}
else
{
[self.player play];
....
}

请注意,我从NSURL的格式为:

  /var/mobile/Applications/xxxxxx/Documents/90989.mp3 


解决方案

从错误中看来, podcastSource 是NSString,如果要请求其路径,则需要为 NSUrl



但是根据Apple文档 dataWithContentsOfFile:接受NSString作为参数,因此无需转换<$ c将$ c> podcastSource 放入 NSUrl 或请求 NSUrl 的路径。 / p>

如果 podcastSource 是完整的文件名,则该文件应该有效:

  NSData * dat一个= [NSData dataWithContentsOfFile:podcastSource]; 


I have a sound player which uses AVAudioPlayer class. I download some items in another view and store the filepath to it as NSURL, then pass the NSURL to the Player viewcontroller. But i get an error while trying to pass the object.

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString path]: unrecognized selector sent to instance 0x1700c86c0'

And here is the code:

NSData *data = [NSData dataWithContentsOfFile:[podcastSource path]];
NSError *error;
mPlayer = [[AVAudioPlayer alloc] initWithData:data error:&error];
[mPlayer setDelegate:self];

if (mPlayer == nil)
{
    NSLog(@"%@",error);
}
else
{
    [self.player play];
....
}

Note that the filePath i receive from the NSURL is in this form:

/var/mobile/Applications/xxxxxx/Documents/90989.mp3

解决方案

From the error it seems as if podcastSource is an NSString when it needs to be an NSUrl if you're going to request its path.

But according to the Apple Docs, dataWithContentsOfFile: accepts an NSString as the argument, so no need to convert podcastSource into an NSUrl or to request that NSUrl's path.

If podcastSource is your filename in its entirety, this should work:

NSData *data = [NSData dataWithContentsOfFile:podcastSource];

这篇关于从本地NSURL转换NSData的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆