Programmatically get path to Application Support folder

IosObjective CSwiftCocoa

Ios Problem Overview


I'm trying to get an NSString for the user's Application Support folder.

I know I can do NSString *path = @"~/Library/Application Support"; but this doesn't seem very elegant. I've played around with using NSSearchPathForDirectoriesInDomains but it seems to be quite long-winded and creates several unnecessary objects (at least, my implementation of it does).

Is there a simple way to do this?

Ios Solutions


Solution 1 - Ios

This is outdated, for current best practice use FileManager.default.urls(for:in:) as in the comment by @andyvn22 below.

the Best practice is to use NSSearchPathForDirectoriesInDomains with NSApplicationSupportDirectory as "long winded" as it may be.

Example:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *applicationSupportDirectory = [paths firstObject];
NSLog(@"applicationSupportDirectory: '%@'", applicationSupportDirectory);

NSLog output:

applicationSupportDirectory: '/Volumes/User/me/Library/Application Support'

Solution 2 - Ios

Swift:

print(NSHomeDirectory())

or

print(FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first)

and

let yourString = String(FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first)

Solution 3 - Ios

Swift 3:

FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first

Solution 4 - Ios

Just to be sure people will start using the recommended way of doing this:

- (NSArray<NSURL *> * _Nonnull)URLsForDirectory:(NSSearchPathDirectory)directory
                                      inDomains:(NSSearchPathDomainMask)domainMask

Expanded example from documentation:

- (NSURL*)applicationDataDirectory {
    NSFileManager* sharedFM = [NSFileManager defaultManager];
    NSArray* possibleURLs = [sharedFM URLsForDirectory:NSApplicationSupportDirectory
                                 inDomains:NSUserDomainMask];
    NSURL* appSupportDir = nil;
    NSURL* appDirectory = nil;
 
    if ([possibleURLs count] >= 1) {
        // Use the first directory (if multiple are returned)
        appSupportDir = [possibleURLs objectAtIndex:0];
    }
 
    // If a valid app support directory exists, add the
    // app's bundle ID to it to specify the final directory.
    if (appSupportDir) {
        NSString* appBundleID = [[NSBundle mainBundle] bundleIdentifier];
        appDirectory = [appSupportDir URLByAppendingPathComponent:appBundleID];
    }
 
    return appDirectory;
}

Proof link: https://developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html#//apple_ref/doc/uid/TP40010672-CH3-SW3

Solution 5 - Ios

This works for me:

NSError *error;
NSURL* appSupportDir = [[NSFileManager defaultManager]     
         URLForDirectory:NSApplicationSupportDirectory
                inDomain:NSUserDomainMask
       appropriateForURL:nil
                  create:YES
                   error:&error];

Solution 6 - Ios

This is what I use to get the database. Got it from the Stanford class. It might help somebody.

NSURL *url = [[[NSFileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"database_name"];
NSLog(@"Database URL: %@",url);

Solution 7 - Ios

Create separate objective C class for reading and writing into documents directory. I will avoid code re-writing. Below is my version of it.

//Directory.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

#define PATH (NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES))
#define BASEPATH (([PATH count] > 0)? [PATH objectAtIndex:0] : nil)

@interface DocumentsDirectory : NSObject

//Here you can also use URL path as return type and file path.
+(void)removeFilesfromDocumentsDirectory:(NSString*)filename;
+(NSString*)writeFiletoDocumentsDirectory:(NSString*)filename;
@end


#import "Directory.h"

@implementation DocumentsDirectory

UIAlertView *updateAlert;

+(void)removeFilesfromDocumentsDirectory:(NSString*)filename
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *filePath = [BASEPATH stringByAppendingPathComponent:filename];

    NSError *error;
    BOOL success = [fileManager removeItemAtPath:filePath error:&error]; //Remove or delete file from documents directory.
    
    if (success)
    {
        updateAlert= [[UIAlertView alloc] initWithTitle:@"Congratulations:" message:@"File is updated successfully" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [updateAlert show];
    }
    else
    {
        NSLog(@"Could not delete file -:%@ ",[error localizedDescription]);
        updateAlert= [[UIAlertView alloc] initWithTitle:@"Try again:" message:[error localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [updateAlert show];
    }
}

+(NSString*)writeFiletoDocumentsDirectory:(NSString*)filename
{
    NSString *foldDestination = BASEPATH;
    NSString *filePath = [foldDestination stringByAppendingPathComponent:filename];

    return filePath;
}

@end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJack JamesView Question on Stackoverflow
Solution 1 - IoszaphView Answer on Stackoverflow
Solution 2 - IosJuan BoeroView Answer on Stackoverflow
Solution 3 - IosAndreas LeyView Answer on Stackoverflow
Solution 4 - IosIvan KarpanView Answer on Stackoverflow
Solution 5 - IosJeff PearceView Answer on Stackoverflow
Solution 6 - IosFlaviuView Answer on Stackoverflow
Solution 7 - IosWasimSafdarView Answer on Stackoverflow