ios Working with Directories in Swift on iOS 10 Finding or creating the application support directory

ios Working with Directories in Swift on iOS 10 Finding or creating the application support directory


Matt Coneybeare

MC

Programmatically Opening the iOS Simulator Data Directory for Your App

| Comments

When developing an app that downloads data and/or creates a lot of data, it is useful to inspect the simulator’s file system to ensure the files are what, and where you expect them to be.
I was tired of having to manually dig in and figure out where these files were being installed to, so I wrote an Xcode Run Script to figure it out for me.

123456789101112131415161718192021
if [ $PLATFORM_NAME = "iphonesimulator" ]then # Get the base directory SIMULATOR_BASE_DIR="/Users/$USER/Library/Application Support/iPhone Simulator/" # Check if it exists if [ -d "$SIMULATOR_BASE_DIR" ]; then # Get the most recent install, i.e. the one we just installed MOST_RECENT_APP=`find "$SIMULATOR_BASE_DIR" -name "$FULL_PRODUCT_NAME" -type d -mtime -365 -print0 | xargs -0 stat -f "%m %N" | sort -rn | head -1 | cut -f2- -d" "` # Get the containing folder MOST_RECENT_APP_DIRECTORY=`dirname "$MOST_RECENT_APP"` # Get the data folder MOST_RECENT_APP_DATA_DIRECTORY="$MOST_RECENT_APP_DIRECTORY/Library/Application Support/$PRODUCT_NAME" # Check if it exists if [ -d "$MOST_RECENT_APP_DATA_DIRECTORY" ]; then # Echo it for debugging echo "Opening $MOST_RECENT_APP_DATA_DIRECTORY" # Open it open -g "$MOST_RECENT_APP_DATA_DIRECTORY" fi fifi

Install it as a run script in your Xcode Target like so:

Example2

It works by using the find command to search the iOS Simulator’s file system for the product name, then grabs the most recently modified one.
If this run script is added after the copy files script, we can be assured that the most recently modified one is the one we just built.
Once we have the most recent product, we find it’s root directory (i.e. app folder) then open up it’s Application Support directory.
You may need to edit the MOST_RECENT_APP_DATA_DIRECTORY= line to suit the directory structure for your specific project. Enjoy

Lastly, I run a small software company called Urban Apps . It pays the bills so I can take the time to write helpful posts like this one. If you found this posting helpful at all, I would really appreciate it if you would check out my Apps on the iTunes App Store.

Comments

My name is Matt Coneybeare , I design and develop for iOS (iPhone, iPad and iPod Touch), Mac OS X and the Web out of New York.
In 2008 I started a software company called Urban Apps that has made some pretty popular apps such as
Ambiance and Hourly News .
My current Stack Overflow reputation is about 27k.

I was a Rockstar a decade ago, but then went back to school and collected a Bachelor’s Degree in Computer Science
from U.C. Berkeley. Now I am settled down with my beautiful wife Di
and our two doggies Hamachi and Foxy .
While coding, I walk several miles/day on my
Treadmill Desk .
When not at my desk, I love exploring New York City as a Yelp Elite ,
or training for marathons.

Contact information

Name
Matt Coneybeare
Email
[email protected]
Website
Twitter
Instagram
GitHub
LinkedIn
Google+

Stack Overflow



  1. Log In
    Sign Up

  2. current community


    • Stack Overflow

      help
      chat

    • Meta Stack Overflow

    your communities

    Sign up or log in to customize your list.

    more stack exchange communities

    company blog

    • Tour

      Start here for a quick overview of the site

    • Help Center

      Detailed answers to any questions you might have

    • Meta

      Discuss the workings and policies of this site

    • About Us

      Learn more about Stack Overflow the company

    • Business

      Learn more about hiring developers or posting ads with us

By using our site, you acknowledge that you have read and understand our Cookie Policy , Privacy Policy , and our Terms of Service .

Programmatically get path to Application Support folder

Ask Question


up vote
49
down vote

favorite

7

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 objective-c swift cocoa

share | improve this question

edited Apr 4 ’17 at 12:15

Cœur

17.3k9102142

asked Dec 8 ’11 at 12:05

Jack James

3,33252834

  • it’s actually ~/Library/Application Support/
    –  Eimantas
    Dec 8 ’11 at 12:07

  • why is this tagged iphone, ipad, and ios?
    –  Dan Rosenstark
    Dec 8 ’11 at 12:24

  • @Eimantas: Yes, corrected OP.
    –  Jack James
    Dec 8 ’11 at 12:34

  • @Yar: it isn’t tagged any of those things
    –  Jack James
    Dec 8 ’11 at 12:35

  • Thanks for fixing that, @Jack.
    –  Dan Rosenstark
    Dec 8 ’11 at 12:59

 | 
show 1 more comment

7 Answers
7

active

oldest

votes


up vote
66
down vote

accepted

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'

share | improve this answer

edited Aug 16 at 2:32

answered Dec 8 ’11 at 12:13

zaph

97.4k18150193

  • That looks a LOT cleaner than what I had. Thank you.
    –  Jack James
    Dec 8 ’11 at 12:36

  • 3

    For swift it’s not preferred method. From docs: You should consider using the FileManager methods urls(for:in:) and url(for:in:appropriateFor:create:). which return URLs, which are the preferred format.
    –  surfrider
    Nov 2 ’17 at 11:43

  • how to create folder in /Library/Application Support of system instead of users /Library/Application Support
    –  Sangram S.
    May 21 at 9:01

  • No because that would be horribly insecure.
    –  zaph
    May 21 at 17:16

  • 1

    This is outdated–the preferred method now is to use FileManager.default.urls(for:in:). In general, Apple is moving towards replacing all string paths with URLs.
    –  andyvn22
    Aug 16 at 1:18

add a comment  | 


up vote
28
down vote

Swift 4:

print(NSHomeDirectory())

or

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

and

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

share | improve this answer

edited Nov 17 ’17 at 14:24

answered Nov 10 ’15 at 20:42

Juan Boero

3,6632847

  • NSHomeDirectory() doesn’t seem to point to the Application Support directory, but rather the outer application sandbox directory. developer.apple.com/documentation/foundation/…
    –  Jeremy Wiebe
    May 31 at 17:19


  • 1

    thanks a bunch. the answer worked, mostly – just wanted to say the URL needs .absoluteString – otherwise you get the error : "Cannot invoke initializer for type ‘String’ with an argument list of type ‘(URL?)’"
    –  sdailey
    Jun 29 at 20:26

  • Note that I used the .url (singular) form, and found the ‘Application Support’ folder did not exist, at least not in the Xcode simulator. So I set the create: true, and it worked fine.
    –  Dave Hubbard
    Nov 1 at 2:25

add a comment  | 


up vote
16
down vote

Swift 3:

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

share | improve this answer

answered Sep 27 ’16 at 7:54

Andreas Ley

8,01813452

add a comment  | 


up vote
6
down vote

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

share | improve this answer

answered Oct 5 ’15 at 10:56

Ivan Karpan

1,3781319

  • Most use the CFBundleExecutable name for the final directory, but you are probably right to advise the use of the bundle ID since it’s more unique. However you have to weigh up wether you might change either the executable or the bundle ID in the future so you can maintain access to the data.
    –  malhal
    Feb 4 ’16 at 18:24


add a comment  | 


up vote
2
down vote

This works for me:

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

share | improve this answer

answered Dec 10 ’15 at 16:44

Jeff Pearce

1114

add a comment  | 


up vote
0
down vote

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);

share | improve this answer

answered Feb 20 ’12 at 20:55

Flaviu

5,11342932

  • 10

    NSDocumentDirectory returns the Documents directory, not the Application Support directory
    –  Lupi
    Feb 12 ’13 at 13:20

  • Just use NSApplicationSupportDirectory instead of NSDocumentDirectory
    –  Dannie P
    Feb 21 ’17 at 11:20

add a comment  | 


up vote
0
down vote

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

share | improve this answer

answered Jul 14 ’16 at 5:58

WasimSafdar

4101725

add a comment  | 

Not the answer you’re looking for? Browse other questions tagged ios objective-c swift cocoa or ask your own question .

asked

7 years ago

viewed

25,914 times

active

3 months ago

Blog

Winter Bash 2018


Linked

33

Application’s data folder in Mac

1

sandboxing an existing OSX app

0

Adding data given by the user to an array – Objective-C

0

How come reading from a plist fails in my iOS application?

0

Objective-C – pathForResource always returns nil

Related

502

How to programmatically send SMS on the iPhone?

750

Can I embed a custom font in an iPhone application?

119

Use C++ with Cocoa Instead of Objective-C?

12

How to incorporate WebSockets into a Cocoa application

376

Applications are expected to have a root view controller at the end of application launch

3

How do I programmatically find the user’s logging directory?

0

iOS Downloading Videos and saving in Application Support folder

605

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

711

Get the length of a String

0

Play a video from a local path

Hot Network Questions

  • Why do modern jets use 20mm guns?

  • How to prevent electronic advancement beyond the early cold war era?

  • How do you make characters relatable if they exist in a completely different moral context?

  • Shady business in the local paper

  • Which is more important in determining author order: time spent or results obtained?

  • How honest should I be in disclosing not-so-exciting results?

  • Does artificial gravity based on centrifugal force stop working if you jump off the ground?

  • How can one individual have two different biological signatures?

  • Do I have to hide anything related to the swastika while travelling to the USA?

  • Derivation of Markov’s Inequality

  • Was the value of thorn ("fawn") pawns fully appreciated in decades past?

  • Why is x == (x = y) not the same as (x = y) == x?

  • Why does an instruction include the address of the next instruction on the IBM 650?

  • Why would having more mages to conduct a spell not make it faster?

  • Do the weights of two liquids not add when mixed?

  • How do I reset the current \AtBeginDocument?

  • Hard Brexit and travel for UK citizens into Schengen countries in 2019

  • Prevent cables of kitchen appliances from breaking when you roll them

  • How to lift a lifetime ban from Canada due to marijuana?

  • Optimal Alphabet Stepping

  • What makes somebody a mandarin?

  • Why are UK MPs targeting the prime minister and not the deal?

  • Convert to Suzhou numerals

  • Why are fuel tanks located in wings?

more hot questions


question feed

default

Stack Overflow works best with JavaScript enabled