Search code examples
iosobjective-ccocoa-touchnsdatansurl

Convert NSData from local NSURL


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

Solution

  • 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];