iOSアプリのドキュメントディレクトリとその使用時期を誰かに説明してもらえますか?
これが私が現在信じていることです:
私には、ユーザーがアプリに必要なファイルを保存できる中央フォルダーのように見えます。
これは、Core Dataがデータを保存する場所とは異なる場所になりますか?
各アプリが独自のドキュメントディレクトリを取得しているようです。
ドキュメントディレクトリ/画像やドキュメントディレクトリ/ビデオなど、ドキュメントディレクトリのサブディレクトリを自由に作成できますか?
iOSアプリのドキュメントディレクトリとその使用時期を誰かに説明してもらえますか?
これが私が現在信じていることです:
私には、ユーザーがアプリに必要なファイルを保存できる中央フォルダーのように見えます。
これは、Core Dataがデータを保存する場所とは異なる場所になりますか?
各アプリが独自のドキュメントディレクトリを取得しているようです。
ドキュメントディレクトリ/画像やドキュメントディレクトリ/ビデオなど、ドキュメントディレクトリのサブディレクトリを自由に作成できますか?
アプリのみ(ジェイルブレイクされていないデバイス上)は「サンドボックス化された」環境で実行されます。これは、独自のコンテンツ内のファイルとディレクトリにのみアクセスできることを意味します。たとえば、ドキュメントとライブラリ。
iOSアプリケーションプログラミングガイドを参照してください。
アプリケーションサンドボックスのDocumentsディレクトリにアクセスするには、次を使用できます。
+ (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
+ (NSString *) applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = paths.firstObject;
return basePath;
}
このドキュメントディレクトリを使用すると、アプリが作成した、または必要になる可能性のあるファイルやサブディレクトリを保存できます。
アプリサンドボックスのライブラリディレクトリ内のファイルにアクセスするには、 (paths
上記の代わりに)次を使用します。
[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]
受け入れられた回答によって提案されたドキュメントでコードを見つけることができませんでしたが、ここで更新された同等のものを見つけました:
ファイルシステムプログラミングガイド::ファイルとディレクトリへのアクセス»
- (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;
}
NSSearchPathForDirectoriesInDomainの使用をお勧めしません。
NSSearchPathForDirectoriesInDomains関数は、URLsForDirectory:inDomains:メソッドのように動作しますが、ディレクトリの場所を文字列ベースのパスとして返します。代わりに、URLsForDirectory:inDomains:メソッドを使用する必要があります。
遊ぶのに役立つ他のディレクトリ定数を次に示します。これらすべてがiOSでサポートされているわけではないことは間違いありません。また、NSHomeDirectory()関数を使用することもできます。
iOSでは、ホームディレクトリはアプリケーションのサンドボックスディレクトリです。OS Xでは、これはアプリケーションのサンドボックスディレクトリまたは現在のユーザーのホームディレクトリです(アプリケーションがサンドボックスにない場合)。
NSPathUtilities.hから
NSApplicationDirectory = 1, // supported applications (Applications)
NSDemoApplicationDirectory, // unsupported applications, demonstration versions (Demos)
NSDeveloperApplicationDirectory, // developer applications (Developer/Applications). DEPRECATED - there is no one single Developer directory.
NSAdminApplicationDirectory, // system and network administration applications (Administration)
NSLibraryDirectory, // various documentation, support, and configuration files, resources (Library)
NSDeveloperDirectory, // developer resources (Developer) DEPRECATED - there is no one single Developer directory.
NSUserDirectory, // user home directories (Users)
NSDocumentationDirectory, // documentation (Documentation)
NSDocumentDirectory, // documents (Documents)
NSCoreServiceDirectory, // location of CoreServices directory (System/Library/CoreServices)
NSAutosavedInformationDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 11, // location of autosaved documents (Documents/Autosaved)
NSDesktopDirectory = 12, // location of user's desktop
NSCachesDirectory = 13, // location of discardable cache files (Library/Caches)
NSApplicationSupportDirectory = 14, // location of application support files (plug-ins, etc) (Library/Application Support)
NSDownloadsDirectory NS_ENUM_AVAILABLE(10_5, 2_0) = 15, // location of the user's "Downloads" directory
NSInputMethodsDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 16, // input methods (Library/Input Methods)
NSMoviesDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 17, // location of user's Movies directory (~/Movies)
NSMusicDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 18, // location of user's Music directory (~/Music)
NSPicturesDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 19, // location of user's Pictures directory (~/Pictures)
NSPrinterDescriptionDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 20, // location of system's PPDs directory (Library/Printers/PPDs)
NSSharedPublicDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 21, // location of user's Public sharing directory (~/Public)
NSPreferencePanesDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 22, // location of the PreferencePanes directory for use with System Preferences (Library/PreferencePanes)
NSApplicationScriptsDirectory NS_ENUM_AVAILABLE(10_8, NA) = 23, // location of the user scripts folder for the calling application (~/Library/Application Scripts/code-signing-id)
NSItemReplacementDirectory NS_ENUM_AVAILABLE(10_6, 4_0) = 99, // For use with NSFileManager's URLForDirectory:inDomain:appropriateForURL:create:error:
NSAllApplicationsDirectory = 100, // all directories where applications can occur
NSAllLibrariesDirectory = 101, // all directories where resources can occur
NSTrashDirectory NS_ENUM_AVAILABLE(10_8, NA) = 102 // location of Trash directory
そして最後に、NSURLカテゴリのいくつかの便利なメソッド http://club15cc.com/code/ios/easy-ios-file-directory-paths-with-this-handy-nsurl-category
グローバル変数としてのSwift3および4:
var documentsDirectory: URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
}
FileManager拡張機能として:
extension FileManager {
static var documentsDirectory: URL {
return `default`.urls(for: .documentDirectory, in: .userDomainMask).last!
}
var documentsDirectory: URL {
return urls(for: .documentDirectory, in: .userDomainMask).last!
}
}
この種の厄介な呼び出しのためにFileManagerに拡張機能を追加する方が、他に何もない場合でも整理するために、よりクリーンになります。何かのようなもの:
extension FileManager {
static var documentDir : URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}
}
このコードを使用してドキュメントディレクトリにアクセスできます。このコードは、基本的にファイルをplist形式で保存するために使用されます。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory;
これは、iOSフォルダの使用/作成を少し簡単にする便利な小さな関数です。
サブフォルダの名前を渡すと、フルパスが返され、ディレクトリが存在することを確認します。
(個人的には、この静的関数をAppDeleteクラスに固定していますが、おそらくこれは最も賢い場所ではありません。)
MySavedImagesサブディレクトリの「フルパス」を取得するための呼び出し方法は次のとおりです。
NSString* fullPath = [AppDelegate getFullPath:@"MySavedImages"];
そして、これが完全な機能です:
+(NSString*)getFullPath:(NSString*)folderName
{
// Check whether a subdirectory exists in our sandboxed Documents directory.
// Returns the full path of the directory.
//
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if (paths.count < 1)
return nil;
NSString *rootFolder = [paths firstObject];
NSString* fullFolderPath = [rootFolder stringByAppendingPathComponent:folderName];
BOOL isDirectory;
NSFileManager* manager = [NSFileManager defaultManager];
if (![manager fileExistsAtPath:fullFolderPath isDirectory:&isDirectory] || !isDirectory) {
NSError *error = nil;
NSDictionary *attr = [NSDictionary dictionaryWithObject:NSFileProtectionComplete
forKey:NSFileProtectionKey];
[manager createDirectoryAtPath:fullFolderPath
withIntermediateDirectories:YES
attributes:attr
error:&error];
if (error) {
NSLog(@"Error creating directory path: %@", [error localizedDescription]);
return nil;
}
}
return fullFolderPath;
}
この小さな関数を使用すると、アプリのDocumentsディレクトリにディレクトリを簡単に作成して(まだ存在しない場合)、そこにファイルを書き込むことができます。
これが私がディレクトリを作成し、それに私の画像ファイルの1つの内容を書き込む方法です:
// Let's create a "MySavedImages" subdirectory (if it doesn't already exist)
NSString* fullPath = [AppDelegate getFullPath:@"MySavedImages"];
// As an example, let's load the data in one of my images files
NSString* imageFilename = @"icnCross.png";
UIImage* image = [UIImage imageNamed:imageFilename];
NSData *imageData = UIImagePNGRepresentation(image);
// Obtain the full path+filename where we can write this .png to, in our new MySavedImages directory
NSString* imageFilePathname = [fullPath stringByAppendingPathComponent:imageFilename];
// Write the data
[imageData writeToFile:imageFilePathname atomically:YES];
お役に立てれば !
他の人が述べたように、アプリはサンドボックス環境で実行され、ドキュメントディレクトリを使用して、アプリが使用する可能性のある画像やその他のアセットを保存できます。ユーザーの好みに応じてoffline-dファイルをダウンロードする-ファイルシステムの基本-Appleのドキュメント-アプリケーション固有のファイルを保存するために使用するディレクトリ
swift 5に更新され、要件に応じてこれらの関数の1つを使用できます-
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
func getCacheDirectory() -> URL {
let paths = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
return paths[0]
}
func getApplicationSupportDirectory() -> URL {
let paths = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
return paths[0]
}
使用法:
let urlPath = "https://jumpcloud.com/wp-content/uploads/2017/06/SSH-Keys.png" //Or string path to some URL of valid image, for eg.
if let url = URL(string: urlPath){
let destination = getDocumentsDirectory().appendingPathComponent(url.lastPathComponent)
do {
let data = try Data(contentsOf: url) //Synchronous call, just as an example
try data.write(to: destination)
} catch _ {
//Do something to handle the error
}
}