ios 以编程方式获取Application Support文件夹路径

vulvrdjw  于 2022-12-05  发布在  iOS
关注(0)|答案(8)|浏览(210)

我正在尝试为用户的“应用程序支持”文件夹获取NSString。
我知道我可以做NSString *path = @"~/Library/Application Support";,但这似乎不是很优雅。我尝试过使用NSSearchPathForDirectoriesInDomains,但它似乎相当冗长,并创建了几个不必要的对象(至少,我的实现是这样)。
有没有简单的方法可以做到这一点?

oknrviil

oknrviil1#

这是过时的,对于当前的最佳实践,请使用FileManager.default.urls(for:in:),如下面@andyvn22的注解所示。
最佳实践是将NSSearchPathForDirectoriesInDomainsNSApplicationSupportDirectory一起使用,因为它可能是“冗长的”。
示例:

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

NSLog输出:

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

py49o6xq2#

斯威夫特:

print(NSHomeDirectory())

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

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

jckbn6z73#

雨燕三号

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

xam8gpfp4#

只是为了确保人们会开始使用推荐的方法来做这件事:

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

文档中的扩展示例:

- (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;
}

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

tez616oj

tez616oj5#

这对我很有效:

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

ecfdbz9o6#

这是我用来获取数据库的。从斯坦福大学的课上拿来的。它可能会帮助一些人。

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

lyfkaqu17#

创建一个单独的目标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
ubby3x7f

ubby3x7f8#

iOS 16更新:URL.applicationSupportDirectory,他们还为documentsDirectory添加了一个静态属性

相关问题