문서 디렉토리 (NSDocumentDirectory)는 무엇입니까?
누군가 iOS 앱의 문서 디렉토리와 사용시기를 설명 할 수 있습니까?
현재 내가 믿는 바는 다음과 같습니다.
나에게 그것은 사용자가 앱에 필요한 모든 파일을 저장할 수있는 중앙 폴더 인 것 같습니다.
Core Data가 데이터를 저장하는 위치와 다른 위치입니까?
각 앱에 자체 문서 디렉토리가있는 것처럼 보입니다.
문서 디렉토리 / 이미지 또는 문서 디렉토리 / 비디오와 같은 문서 디렉토리의 하위 디렉토리를 자유롭게 만들 수 있습니까?
앱이 탈옥되지 않은 기기에서만 "샌드 박스형"환경에서 실행됩니다. 이는 자체 컨텐츠 내의 파일 및 디렉토리에만 액세스 할 수 있음을 의미합니다. 예를 들어 문서 및 라이브러리 입니다.
iOS 애플리케이션 프로그래밍 안내서를 참조하십시오 .
응용 프로그램 샌드 박스 의 Documents 디렉토리에 액세스하려면 다음을 사용할 수 있습니다.
iOS 8 이상에서 권장되는 방법입니다.
+ (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
iOS 7 이하를 지원해야하는 경우
+ (NSString *) applicationDocumentsDirectory
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = paths.firstObject;
return basePath;
}
이 문서 디렉토리를 사용하면 앱에서 작성하거나 필요할 수있는 파일 및 하위 디렉토리를 저장할 수 있습니다.
앱 샌드 박스 의 라이브러리 디렉토리 에있는 파일에 액세스하려면 paths
위 대신 사용하십시오 .
[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0]
이것은 iOS 8에서 변경되었습니다. 다음 기술 노트를 참조하십시오. https://developer.apple.com/library/ios/technotes/tn2406/_index.html
위의 링크에서 Apple이 승인 한 방식은 다음과 같습니다.
// Returns the URL to the application's Documents directory.
- (NSURL *)applicationDocumentsDirectory
{
return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}
수락 된 답변이 제안한 문서에서 코드를 찾을 수 없지만 여기에서 업데이트 된 동등한 것을 발견했습니다.
파일 시스템 프로그래밍 안내서 :: 파일 및 디렉토리 액세스»
- (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
And finally, some convenience methods in an NSURL category http://club15cc.com/code/ios/easy-ios-file-directory-paths-with-this-handy-nsurl-category
Swift 3 and 4 as global var:
var documentsDirectory: URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last!
}
As FileManager extension:
extension FileManager {
static var documentsDirectory: URL {
return `default`.urls(for: .documentDirectory, in: .userDomainMask).last!
}
var documentsDirectory: URL {
return urls(for: .documentDirectory, in: .userDomainMask).last!
}
}
Aside from the Documents
folder, iOS also lets you save files to the temp
and Library
folders.
For more information on which one to use, see this link from the documentation:
It can be cleaner to add an extension to FileManager for this kind of awkward call, for tidiness if nothing else. Something like:
extension FileManager {
static var documentDir : URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}
}
You can access documents directory using this code it is basically used for storing file in plist format:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory;
Here's a useful little function, which makes using/creating iOS folders a little easier.
You pass it the name of a subfolder, it'll return the full path back to you, and make sure the directory exists.
(Personally, I stick this static function in my AppDelete class, but perhaps this isn't the smartest place to put it.)
Here's how you would call it, to get the "full path" of a MySavedImages subdirectory:
NSString* fullPath = [AppDelegate getFullPath:@"MySavedImages"];
And here's the full function:
+(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;
}
Using this little function, it's easy to create a directory in your app's Documents directory (if it doesn't already exist), and to write a file into it.
Here's how I would create the directory, and write the contents of one of my image files into it:
// 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];
Hope this helps !
참고URL : https://stackoverflow.com/questions/6907381/what-is-the-documents-directory-nsdocumentdirectory
'Programing' 카테고리의 다른 글
LocalDate를 문자열로 포맷하는 방법은 무엇입니까? (0) | 2020.07.15 |
---|---|
MVC에서 기본 경로 (영역으로)를 설정하는 방법 (0) | 2020.07.15 |
모키 토 : InvalidUseOfMatchersException (0) | 2020.07.15 |
불투명도 : 0은 가시성 : 숨김과 효과가 동일합니다. (0) | 2020.07.15 |
파일의 확장자를 찾는 방법? (0) | 2020.07.15 |