make folder in sand box of osx - macos

using the code below to get the file path:
NSString *executableName = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"CFBundleExecutable"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *path = [paths objectAtIndex:0];
path = [path stringByAppendingPathComponent:executableName];
then I want to save data to the file (settings.bundle)
NSString *filePath = [path stringByAppendingPathComponent:#"settings.bundle"];
[someString writeToFile:settingsPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
the error:
Error Domain=NSCocoaErrorDomain Code=4 "The folder “settings.bundle” doesn’t exist." UserInfo=0x7ff8894cecc0 {NSFilePath=/Users/xxxx/Library/Application Support/AppName/settings.bundle, NSUserStringVariant=Folder, NSUnderlyingError=0x7ff8894a1750 "The operation couldn’t be completed. No such file or directory"}
but if I mkdir AppName manual there is no error:
mkdir /Users/xxxx/Library/Application Support/AppName
So My question is : Cocoa can NOT create folder automaticly in osx?

Give this a shot: [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:&error];
That method will create not only the directory at the specified path, but also any intermediate ones that may not exist.

Related

Path for downloads OSX 10.10.5 and xcode 7.2.1

I made for our internal use a app with a today-extension. There I have access to download all files from our server. But I did not get the right path to save it. I want to save it in the users "downloads" or on the users "desktop".
My code to save the file is:
NSArray *docDirs = NSSearchPathForDirectoriesInDomains(NSDownloadsDirectory,NSUserDomainMask, YES);
NSString *doc = [docDirs objectAtIndex:0];
NSString *filePath = [NSString stringWithFormat:#"%#/Page1.pdf", doc];
dispatch_async(dispatch_get_main_queue(), ^{
[urlData writeToFile:filePath atomically:YES];
This saves the file
/Users/itsMe/Library/Containers/com.myCompany.downloadApp.ToDayWidget/Data/Downloads/Page1.pdf
I want to save the file in /users/itsMe/Downloads/Page1.pdf or /users/itsMe/Desktop/Page1.pdf.
How can I do this? I tried without success modifying the path:
NSString *homeDir = NSHomeDirectory();
NSString *homeDir1 = [homeDir stringByDeletingLastPathComponent];
NSString *homeDir2 = [homeDir1 stringByDeletingLastPathComponent];
NSString *homeDir3 = [homeDir2 stringByDeletingLastPathComponent];
NSString *homeDir4 = [homeDir3 stringByDeletingLastPathComponent];
NSString *filePath = [NSString stringWithFormat:#"%#/Page1.pdf", homeDir4];
To access the ~/Downloads folder add the com.apple.security.files.downloads.read-write entitlement by setting File Access > Downloads Folder in the Capabilities > App Sandbox section to Read/Write.
~/Desktop is not accessible outside the sandbox.

how to play an audio file which is not in the main bundle?

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.m‌​p3 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.

Zip from command line - how to trim path elements

I'm executing a zip command from within my app using NSTask. It's passed as arguments some paths which point to the files/folders to be zipped.
The problem is that without the -j option, the final zip ends up with absurd filepaths inside the zip, (like "/private/var/folders/A5/A5CusLQaEo4mop-reb-SYE+++TI/-Tmp-/9101A216-5A6A-4CD6-A477-E4B86E007476-51228-00014BCB9514323F/myfile.rtf"). However, if I add the -j option, then I constantly run into name collisions if any file anywhere deep inside a nested folder has
I've tried setting the path before executing the NSTask:
[[NSFileManager defaultManager] changeCurrentDirectoryPath:path];
In the hope that the documentation for zip was telling the truth:
By default, zip will store the full path
(relative to the current directory)
But this did not work as expected. Adjusting settings of -j and -p and -r simply produces the above mentioned problems in different combinations.
QUESTION:
How can I take a set of directories like
/some/long/path/sub1/file1.txt
/some/long/path/sub2/file1.txt
and zip them into a zip whose contents are
/sub1/file1.txt
/sub2/file1.txt
Thanks for any advice on the subtleties of zip.
-----EDIT
One other thing I forgot to add is that the original directory being passed is "path", so the desired outcome is also to my mind the expected outcome.
Instead of
[[NSFileManager defaultManager] changeCurrentDirectoryPath:path];
use -[NSTask setCurrentDirectoryPath:] prior to launching the task. For example:
NSString *targetZipPath = #"/tmp/foo.zip";
NSArray *args = [NSArray arrayWithObjects:#"-r", targetZipPath,
#"sub1", #"sub2", nil];
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:#"/usr/bin/zip"];
[task setArguments:args];
// set path to be the parent directory of sub1, sub2
[task setCurrentDirectoryPath:path];
…
This is not a universal solution, in that it won't handle multiple directories well, but the solution I'm using for a single directory of unknown contents (ie, mixed files/folders/bundles) is to enumerate the contents of the directory and add them individually as arguments to zip, rather than simply zipping the entire directory at once.
Specifically:
+ (BOOL)zipDirectory:(NSURL *)directoryURL toArchive:(NSString *)archivePath;
{
//Delete existing zip
if ( [[NSFileManager defaultManager] fileExistsAtPath:archivePath] ) {
[[NSFileManager defaultManager] removeItemAtPath:archivePath error:nil];
}
//Specify action
NSString *toolPath = #"/usr/bin/zip";
//Get directory contents
NSArray *pathsArray = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:[directoryURL path] error:nil];
//Add arguments
NSMutableArray *arguments = [[[NSMutableArray alloc] init] autorelease];
[arguments insertObject:#"-r" atIndex:0];
[arguments insertObject:archivePath atIndex:0];
for ( NSString *filePath in pathsArray ) {
[arguments addObject:filePath]; //Maybe this would even work by specifying relative paths with ./ or however that works, since we set the working directory before executing the command
//[arguments insertObject:#"-j" atIndex:0];
}
//Switch to a relative directory for working.
NSString *currentDirectory = [[NSFileManager defaultManager] currentDirectoryPath];
[[NSFileManager defaultManager] changeCurrentDirectoryPath:[directoryURL path]];
//NSLog(#"dir %#", [[NSFileManager defaultManager] currentDirectoryPath]);
//Create
NSTask *task = [[[NSTask alloc] init] autorelease];
[task setLaunchPath:toolPath];
[task setArguments:arguments];
//Run
[task launch];
[task waitUntilExit];
//Restore normal path
[[NSFileManager defaultManager] changeCurrentDirectoryPath:currentDirectory];
//Update filesystem
[[NSWorkspace sharedWorkspace] noteFileSystemChanged:archivePath];
return ([task terminationStatus] == 0);
}
Again, I make no claims this is bulletproof (and would love improvements) but it does work at correctly zipping any single folder.

NSFileWriteNoPermissionError when trying to create a new directory in /Library/Application Support/

The following code returns a NSCocoaErrorDomain with error code 513 (NSFileWriteNoPermissionError) when running from xcode.
NSError *error;
[[NSFileManager defaultManager]
createDirectoryAtPath:#"/Library/Application Support/myapp"
withIntermediateDirectories:YES
attributes:nil
error:&error];
This is on a Mac OS X 10.6.7, the specified directory does not exist, and my user has admin privileges.
The purpose is to save application support files that are shared among users. Shouldn't there be write permissions to create this directory?
No, that's the system's Library folder. You need the user's Library, at "~/Library/". You could try:
[NSHomeDirectory() stringByAppendingPathComponent:#"Library/Application Support/myapp"]
or:
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString * appSupportPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"myapp"];
Just for one more option, you can also get a URL from the file manager:
NSFileManager * fm = [[NSFileManager alloc] init];
NSArray * urls = [fm URLsForDirectory:NApplicationSupportDirectory inDomains:NSUserDomainMask];
NSURL * appSupportURL = [urls objectAtIndex:0];

Problems with UIImagePNGRepresentation

I'm trying to use this line of code
[UIImagePNGRepresentation(image, 1.0) writeToFile:pngPath atomically:YES];
But obviously pngPath is undeclared. So I have to use stringByAppendingPathComponent.
I googled examples of this, and I found this
myPlistPath = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithFormat: #"%#.plist", plistName] ];
[myPlistPath retain]
;
The problem is that I don't have a plist file, because I don't need one. How can I solve all these issues and writeToFile the UIImage image?
I don't fully understand your question, but to get the full path where your file should be saved, you could try this:
NSString *file = #"myfile.png";
NSString *directory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
NSString *path = [directory stringByAppendingPathComponent: file];
and then:
[UIImagePNGRepresentation(image) writeToFile:path atomically:YES];

Resources