iPod Library path to NSData - ios

How to convert the iPod library to NSData.
The url is:
ipod-library://item/item.mp3?id=1258203422631791096
Getting error but, I can play the song by using AVPlayer.
NSURL *url = [curItem valueForProperty: MPMediaItemPropertyAssetURL];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfFile:[url absoluteString] options:NSDataReadingMappedAlways error:&error];
NSLog(#"Error : %#",error);
The curItem is a MPMediaItem
Error Domain=NSCocoaErrorDomain Code=260 "The file “item.mp3?id=1258203422631791096” couldn’t be opened because there is no such file." UserInfo={NSFilePath=ipod-library://item/item.mp3?id=1258203422631791096, NSUnderlyingError=0x15ff23420 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

You cannot access the media item URL directly, as it resides outside your application's sandbox.
You need to fetch the asset using AVAssetExportSession that saves it to an URL in your sandbox. You can get NSData from there – see this SO question iOS 6 issue Convert MPMediaItem to NSData

Related

NSData dataWithContentsOfURL for URL from camera roll

I have some URLs for the videos stored in camera rolls. For example:
file:///var/mobile/Media/DCIM/100APPLE/IMG_0249.MP4
I would like to further process those videos as NSData, but if I use
NSURL* videoURL = [NSURL fileURLWithPath:#"file:///var/mobile/Media/DCIM/100APPLE/IMG_0249.MP4"];
NSData *imageData = [NSData dataWithContentsOfURL:videoURL options:NSDataReadingMappedIfSafe error:&error];
The data is always nil. And I get the following error:
Error Domain=NSCocoaErrorDomain Code=257 "The file “IMG_0249.MP4”
couldn’t be opened because you don’t have permission to view it."
UserInfo={NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0249.MP4,
NSUnderlyingError=0x165351d0 {Error Domain=NSPOSIXErrorDomain Code=1
"Operation not permitted"}}
I noticed that if the URL is from my local app document folder, I can generate NSData without any issues. I wonder if it's not allowed to create NSData out of the videos stored in Camera Roll. I wonder if I need to use the Photos framework or some other method in order to have the permission.
It turns out that I can't turn a URL for Camera Rolls videos into NSData directly, I need to use PHImageManager to do that (And use the localIdentifier of the PHAsset of the video I acquired in the past):
PHFetchResult* assets = [PHAsset fetchAssetsWithLocalIdentifiers:#[videoID] options:nil];
PHAsset *asset = assets.firstObject;
if (asset.mediaType == PHAssetMediaTypeVideo) {
[[PHImageManager defaultManager] requestAVAssetForVideo:asset options:nil resultHandler:^(AVAsset *asset, AVAudioMix *audioMix, NSDictionary *info) {
if ([asset isKindOfClass:[AVURLAsset class]]) {
AVURLAsset* urlAsset = (AVURLAsset*)asset;
NSData *data = [NSData dataWithContentsOfURL:urlAsset.URL];
[self sendToTwitter:data withMessage:message account: account];
}
}];
}
My guess is that the AVURLAsset* urlAsset has some additional permission info that my previous approach through [NSURL fileURLWithPath] doesn't have.

NSFileManager Create Directory Failed with Error Code 513

There is a horrible bug which is only occurring intermittently. I'm trying to save data into a sub-folder in 'Application Support' folder. Before saving I will create that sub-folder if not exists
NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES).firstObject;
NSString *packagePath = [cachePath stringByAppendingPathComponent:#"ResourcePackage"];
NSError *error = nil;
BOOL isDirectory = NO;
if(![[NSFileManager defaultManager] fileExistsAtPath:packagePath isDirectory:&isDirectory] || !isDirectory)
{
[[NSFileManager defaultManager] createDirectoryAtPath:packagePath withIntermediateDirectories:YES attributes:nil error:&error];
}
Everything goes fine but except for only one device on which will get error with code 513
Error Domain=NSCocoaErrorDomain Code=513 "您没有将文件“ResourcePackage”存储到文件夹“Application Support”中的权限。" UserInfo={NSFilePath=/var/mobile/Containers/Data/Application/4FF643C4-D568-417F-9A88-5E9FF2326972/Library/Application Support/ResourcePackage, NSUnderlyingError=0x17425e6f0 {Error Domain=NSPOSIXErrorDomain Code=13 "Permission denied"}}
What have I missed or am I doing wrong while writing to this directory?
Thanks!

MP3 file from server is not playing with AVAudioPlayer in iOS7

Here is my code, In this first I am calling mp3 url for downloading the audio data. then I am saving that data in local directory, After that I am playing audio from local file path but its not working AVAudioPlayer throwing error. I have tried some other ways also but no one work for me.
On simulator same code is working fine.
And the audio url is playing like a charm in browser.
NSURL *urlll=[NSURL URLWithString:#"www.xyz.audio.mp3"];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:urlll] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *responce,NSData* data,NSError * error) {
if (error == nil)
{
indicator.hidden=YES;
[indicator stopAnimating];
if (data)
{
NSString *docDirPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/%#.mp3", docDirPath , #"Audio"];
[data writeToFile:filePath atomically:YES];
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:fileURL error:&error];
AudioPlayer.delegate=self;
[AudioPlayer prepareToPlay];
if (AudioPlayer == nil) {
NSLog(#"AudioPlayer did not load properly: %#", [error description]);
} else {
[AudioPlayer play];
}
}
}
}];
But I am getting these kind of errors : Error Domain=NSOSStatusErrorDomain Code=1685348671 "The operation couldn't be completed. (OSStatus error 1685348671.)
Please Help me :( .
In your code you save the audio to NSString *filePath but you initiate with fileURL. Could it be that you actually wanted to do this:
AudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:filePath] error:&error];
If not then you should know that the error is reporting to you a kAudioFileInvalidFileError. Which means the file is malformed. You could try other formats like .caf or .aifc or aiff.
--edit--
Make sure the AVAudioPlayer is a property in .m or .h file, so the memory allocation lasts after leaving the method:
#property (nonatomic,strong) AVAudioPlayer *AudioPlayer;
(side note: properties should start with lowercase -> audioPlayer)

Incorrect URL for AVURLAsset

I am preparing the URL for one method of AVURLAsset:
+ (AVURLAsset *)URLAssetWithURL:(NSURL *)URL options:(NSDictionary *)options
My URL belongs to a file which is written to the document path of my app. The result of NSLog the path is:
/var/mobile/Containers/Data/Application/E0E64E72-9A47-4E62-B9C6-818AB8BF3F4C/Documents/audio.wav
After got the NSString *path, I tried to convert NSString to NSURL by [NSURL URLWithString:path] and [NSURL fileURLWithPath:path], but both of them are incorrect for URLAssetWithURL.
Error of URLWithString is:
Error Domain=AVFoundationErrorDomain Code=-11800 "The operation could
not be completed" UserInfo=0x170269f80 {NSUnderlyingError=0x17405f440
"The operation couldn’t be completed. (OSStatus error -12780.)",
NSLocalizedFailureReason=An unknown error occurred (-12780),
NSLocalizedDescription=The operation could not be completed}
And fileURLWithPath crashed the app.
I know url = [[NSBundle mainBundle] URLForResource:fileURL withExtension:#"wav"] will fit the situation. But I want to get the url of a local file to fit URLAssetWithURL as well. Any idea? Thanks.
This way of getting a file from the documents should work:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths.firstObject stringByAppendingPathComponent:#"file"] stringByAppendingPathExtension:#"wav"];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSURL *url = [NSURL fileURLWithPath:path];
}

Path to file in app bundle

I did this many times before but now it fails.
I want to access a file shipped within my app.
NSString* path = [[NSBundle mainBundle] pathForResource:#"information" ofType:#"xml"];
returns
/Users/eldude/Library/Application Support/iPhone Simulator/7.0.3/Applications/5969FF96-7023-4859-90C0-D4D03D25998D/App.app/information.xml
which is correct - checked in terminal and all that. However, trying to parse the path fails
NSURL* fileURL = [NSURL URLWithString:path];
NSXMLParser *nsXmlParser = [[NSXMLParser alloc] initWithContentsOfURL:fileURL];
[nsXmlParser setDelegate:self];
if(![nsXmlParser parse]){
NSError* e = nsXmlParser.parserError;
NSLog(#"ERROR parsing XML file: \n %#",e);
self = NULL;
}
with
Error Domain=NSCocoaErrorDomain Code=-1 "The operation couldn’t be completed. (Cocoa error -1.)" UserInfo=0xb9256f0 {NSXMLParserErrorMessage=Could not open data stream}
Ideas anyone?
File URLs and network URLs are different.
From the Apple documentation:
Important: To create NSURL objects for file system paths, use
fileURLWithPath:isDirectory:
or just
fileURLWithPath:
Example:
NSString *filePath = #"path/file.txt";
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
NSLog(#"fileURL: %#", [fileURL absoluteURL]);
NSURL *netURL = [NSURL URLWithString:filePath];
NSLog(#"netURL: %#", [netURL absoluteURL]);
NSLog Output:
fileURL: file:///path/file.txt
netURL: path/file.txt

Resources