ios 以编程方式获取应用程序支持文件夹的路径

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8430777/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:47:53  来源:igfitidea点击:

Programmatically get path to Application Support folder

iosobjective-cswiftcocoa

提问by Hyman James

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

我正在尝试为用户的应用程序支持文件夹获取 NSString。

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

我知道我可以做到,NSString *path = @"~/Library/Application Support";但这似乎不太优雅。我玩过 usingNSSearchPathForDirectoriesInDomains但它似乎很冗长,并创建了几个不必要的对象(至少,我的实现是这样)。

Is there a simple way to do this?

有没有一种简单的方法可以做到这一点?

回答by zaph

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

这是过时的,对于当前的最佳实践使用,FileManager.default.urls(for:in:)如下面@andyvn22的评论所示。

the Best practice is to use NSSearchPathForDirectoriesInDomainswith NSApplicationSupportDirectoryas "long winded" as it may be.

最好的做法是使用NSSearchPathForDirectoriesInDomainsNSApplicationSupportDirectory“长气”,因为它可能。

Example:

例子:

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

NSLog output:

NSLog 输出:

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

回答by Juan Boero

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)

回答by Andreas Ley

Swift 3:

斯威夫特 3:

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

回答by Ivan Karpan

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

证明链接:https: //developer.apple.com/library/ios/documentation/FileManagement/Conceptual/FileSystemProgrammingGuide/AccessingFilesandDirectories/AccessingFilesandDirectories.html#//apple_ref/doc/uid/TP40010672-CH3-SW3

回答by Jeff Pearce

This works for me:

这对我有用:

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

回答by WasimSafdar

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

创建单独的目标 C 类,用于读取和写入文档目录。我将避免重新编写代码。下面是我的版本。

//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

回答by Flaviu

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