My iOS app wants to play a local audio file. So, in xCode, I’ve added a file "audio.m4a" to my project. It resides on the top level of the file tree, but
NSURL *audioFileURL = [[NSBundle mainBundle]
URLForResource:#"audio"
withExtension:#"m4a"];
returns nil. There must be a stupid oversight. What am I doing wrong?
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *myFile = [mainBundle pathForResource: #"audio" ofType: #"m4a"];
NSURL *audioFileURL = [NSURL URLWithString:myFile];
and check whether that file present in Build Phases" -> "copy bundle Resources"
Swift
Since neither answer is complete, and the solution is disseminated in the comments, let me offer a Swift alternative. and a step-by-step response.
The original Objective-C code is correct:
NSURL *audioFileURL = [[NSBundle mainBundle]
URLForResource:#"audio"
withExtension:#"m4a"];
Swift
let audioFileURL = NSBundle.mainBundle().URLForResource(
"audio",
withExtension: "m4a")
Target Membership
This was probably an oversight when originally adding the resource to the project. You must select adequate targets when adding these files:
Regardless of the language, ensure that your file is Project > Build Phases > Copy Bundle Resources. You need not to do that by hand. Instead, use the File Inspector. Select your resource (on the left panel) and verify it's target membership (on the right panel):
/* Use this code to play an audio file */
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"m4a"];
NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];
player.numberOfLoops = -1; //Infinite
[player play];
Related
The App Sandbox design guide says:
The related items feature of App Sandbox lets your app access files
that have the same name as a user-chosen file, but a different
extension. This feature consists of two parts: a list of related
extensions in the application’s Info.plist file and code to tell the
sandbox what you’re doing.
My Info.plist defines a document type for .pnd files (the user-chosen file), as well as a document type for .bak files. The entry for the .bak files has, among other properties, the property NSIsRelatedItemType = YES.
I am trying to use Related Items to move an existing file to a backup file (change .pnd suffix to .bak suffix) when the user writes a new version of the .pnd file. The application is sandboxed. I am not proficient with sandboxing.
I am using PasteurOrgManager as the NSFilePresenter class for both the original and backup files:
#interface PasteurOrgData : NSObject <NSFilePresenter>
. . . .
#property (readonly, copy) NSURL *primaryPresentedItemURL;
#property (readonly, copy) NSURL *presentedItemURL;
#property (readwrite) NSOperationQueue *presentedItemOperationQueue;
#property (readwrite) NSFileCoordinator *fileCoordinator;
. . . .
- (void) doBackupOf: (NSString*) path;
. . . .
#end
The doBackupOf: method is as follows. Notice that it also sets the NSFilePresenter properties:
- (void) doBackupOf: (NSString*) path
{
NSError *error = nil;
NSString *appSuffix = #".pnd";
NSURL *const pathAsURL = [NSURL URLWithString: [NSString stringWithFormat: #"file://%#", path]];
NSString *const baseName = [pathAsURL lastPathComponent];
NSString *const prefixToBasename = [path substringToIndex: [path length] - [baseName length] - 1];
NSString *const baseNameWithoutExtension = [baseName substringToIndex: [baseName length] - [appSuffix length]];
NSString *backupPath = [NSString stringWithFormat: #"%#/%#.bak", prefixToBasename, baseNameWithoutExtension];
NSURL *const backupURL = [NSURL URLWithString: [NSString stringWithFormat: #"file://%#", backupPath]];
// Move backup to trash — I am sure this will be my next challenge
// (it's a no-op now because there is no pre-existing .bak file)
[[NSFileManager defaultManager] trashItemAtURL: backupURL
resultingItemURL: nil
error: &error];
// Move file to backup
primaryPresentedItemURL = pathAsURL;
presentedItemURL = backupURL;
presentedItemOperationQueue = [NSOperationQueue mainQueue];
[NSFileCoordinator addFilePresenter: self];
fileCoordinator = [[NSFileCoordinator alloc] initWithFilePresenter: self]; // error here
[self backupItemWithCoordinationFrom: pathAsURL
to: backupURL];
[NSFileCoordinator removeFilePresenter: self];
fileCoordinator = nil;
}
The backupItemWithCoordinationFrom: method does the heavy lifting, basically:
[fileCoordinator coordinateWritingItemAtURL: from
options: NSFileCoordinatorWritingForMoving
error: &error
byAccessor: ^(NSURL *oldURL) {
[self.fileCoordinator itemAtURL: oldURL willMoveToURL: to];
[[NSFileManager defaultManager] moveItemAtURL: oldURL
toURL: to
error: &error];
[self.fileCoordinator itemAtURL: oldURL didMoveToURL: to];
}
but the code doesn't make it that far. I have traced the code and the URL variables are as I expect, and are reasonable. At the point of "error here" in the above code, where I allocate the File Presenter, I get:
NSFileSandboxingRequestRelatedItemExtension: an error was received from pboxd instead of a token. Domain: NSPOSIXErrorDomain, code: 1
[presenter] +[NSFileCoordinator addFilePresenter:] could not get a sandbox extension. primaryPresentedItemURL: file:///Users/cope/Me.pnd, presentedItemURL: file:///Users/cope/Me.bak
Any help is appreciated.
(I have read related posts Where can a sandboxed Mac app save files? and Why do NSFilePresenter protocol methods never get called?. I have taken note of several other sandboxing-related posts that don't seem relevant to this issue.)
MacBook Pro, MacOS 10.13.5, XCode Version 9.3 (9E145)
do not read too much about avoiding sandboxing. Most explenations go too far out of the most obvious problem. Instead of explaining the pitfalls that rightfully triggers sandboxing they explain mostly how to avoid the Sandbox at all. Which is not a solution - it is a thread!
So the most obvious problem is exposing a URL to pasteboard that still needs properly escaped characters in the string before you transform to NSURL.
So your NSString beginning with "file://" should use something like..
NSString *encodeStringForURL = [yourstring stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
before you transform to NSURL with
NSURL *fileurl = [NSURL URLWithString:encodeStringForURL];
NString *output = fileurl.absoluteString;
For whatever reason, I'm not having the UIImage appear on my desktop. I'm using this code as a means of debugging. However, I'm pretty sure that I am receiving an image since the UIImage in the debugger is not null.
UIImage *imgageProfile = [UIImage imageWithData:
[NSData dataWithContentsOfURL:
[NSURL URLWithString: sUrlPic]]];
// Use this code to debug images
NSURL *aLocalURL = [NSURL URLWithString:#"file:///Users/snuffles753/Desktop/"];
NSData *imageData = UIImagePNGRepresentation(imgageProfile);
[imageData writeToURL:aLocalURL atomically:YES];
-[NSData writeToURL:…] takes a URL that includes the name of the file you'd like created. It will `not take the URL of a folder, and automatically create a file inside of that. So your current code is attempting to overwrite an existing directory, which then fails.
Instead, specify the filename explicitly:
NSURL *aLocalURL = [NSURL URLWithString:#"file:///Users/snuffles753/Desktop/debug.png"];
this is my code to play mp3 file from the directory of the application, and for some reason it's not working. lease find out what's wrong with this code !
-(IBAction)PlayLesson:(id)sender;
{
NSString *folderAndFile = #"/Users/alaaalfadhel/Library/Application Support/iPhone Simulator/5.1/Applications/1021CF5B-F664-4123-B9CB-529217225B74/Documents/file.mp3";
NSString *audioFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:folderAndFile];
NSURL *url = [NSURL fileURLWithPath:audioFilePath];
ofType:#"mp3"]];
AVAudioPlayer *click = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
[click play];
}
Since the NSSearchPathForDirectoriesInDomains supplies everything up to the Documents directory, you don't need to give it a folder/file combination but just the file.
You really want your URL to be /Users/alaaalfadhel/Library/Application Support/iPhone Simulator/5.1/Applications/5515AFBA-1E7D-4B06-A62E-F6FDFD7DD7C7/Documents/file.mp3 instead of the one displayed in your log. This is necessary because the long hex value will change any time you remove the app from the simulator and then launch it again.
How to retrieve all app bundle IDs which can open file at given URL? Like if file at given URL is .xml I want to get array of all app bundle IDs which can open .xml.
You can use Launch Services' LSCopyAllRoleHandlersForContentType() to get an array of bundle identifiers of capable applications.
Code might look something like the following:
NSURL *fileURL = [[NSBundle mainBundle] URLForResource:#"sample"
withExtension:#"xml"];
NSString *utiType = nil;
NSError *error = nil;
BOOL success = [fileURL getResourceValue:&utiType
forKey:NSURLTypeIdentifierKey error:&error];
if (!success) {
NSLog(#"getResourceValue:forKey:error: returned error == %#", error);
}
NSArray *bundleIdentifiers = [(NSArray *)LSCopyAllRoleHandlersForContentType(
(CFStringRef)utiType, kLSRolesAll) autorelease];
NSLog(#"bundleIdentifiers == %#", bundleIdentifiers);
In most recent versions of OS X, Launch Services is part of the CoreServices.framework umbrella framework. You may need to #import it in the class you want to call the LS* functions in, as well as add it to the Link Binary With Libraries Build Phase of your target. (It seemed to work OK here without linking against it in the OS X 10.8 SDK).
my code is this. And the value of ret is always NO, I think the write path is not allowed.
But where I can store my information on MAC OS X for my app? Can you help me to find the right path to store my app's setting? Thank you very much~ :)
NSString* writePath = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:#"Brain.plist"];
NSLog(#"%#",writePath);
NSMutableDictionary* dictForRet = [[NSMutableDictionary alloc]init];
NSNumber* applicationNumber = [[NSNumber alloc]initWithInt:0];
NSMutableDictionary* root = [[NSMutableDictionary alloc]init];
NSArray* propertyArray = [[NSArray alloc]initWithObjects:kPropertyArrayApplicationPath,kPropertyArrayApplicationCS, nil];
NSMutableDictionary* brain = [[NSMutableDictionary alloc]init];
[root setObject:propertyArray forKey:kPropertyArrayName];
[dictForRet setObject:applicationNumber forKey:kPropertyKeyApplicationNumber];
[dictForRet setObject:root forKey:kPropertyArrayDictName];
[dictForRet setObject:brain forKey:kPropertyDictBrainName];
NSLog(#"%#",dictForRet);
ret = [dictForRet writeToFile:writePath atomically:YES];
NSLog(#"%d",ret);
The resource path refers to the Resources/ directory in your app bundle. You do not want to write to this path, which is usually not allowed (especially in case of a sandboxed app).
To get paths to standard locations, like the Application Support directory use NSSearchPathForDirectoriesInDomains.
You're probably looking for something like:
NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
This will return an (array of size 1) Application Support URL, automatically picking the right path if your app is sandboxed.
You can't write to the current app's bundle.
Instead, you might stuff it in your sandbox, in ~/Library/Application Support/YOUR_APP/, or in a user-specified location.