반응형
리소스 폴더에서 파일 목록 가져오기 - iOS
예를 들어 제 아이폰 애플리케이션의 "리소스" 폴더에 "문서"라는 폴더가 있다고 가정해 보겠습니다.
실행 시 해당 폴더에 포함된 모든 파일의 배열이나 목록을 얻을 수 있는 방법이 있습니까?
코드상으로는 다음과 같습니다.
NSMutableArray *myFiles = [...get a list of files in Resources/Documents...];
가능한가요?
당신은 그 길을 갈 수 있습니다.Resources
이런 디렉토리,
NSString * resourcePath = [[NSBundle mainBundle] resourcePath];
그 다음에 추가합니다.Documents
오솔길로,
NSString * documentsPath = [resourcePath stringByAppendingPathComponent:@"Documents"];
그러면 당신은 API를 나열하는 디렉토리를 사용할 수 있습니다.NSFileManager
.
NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:&error];
참고: 소스 폴더를 번들에 추가할 때 "복사할 때 추가된 폴더에 대한 폴더 참조 만들기 옵션"을 선택해야 합니다.
스위프트
Swift 3용으로 업데이트됨
let docsPath = Bundle.main.resourcePath! + "/Resources"
let fileManager = FileManager.default
do {
let docsArray = try fileManager.contentsOfDirectory(atPath: docsPath)
} catch {
print(error)
}
추가 읽기:
- NSFileManager 클래스 참조
- 파일 시스템 프로그래밍 가이드
- 문서 처리 오류
- Swift 2.0 블로그 게시물의 오류 처리
- 스위프트에서 메소드가 던질 수 있는 오류를 찾아 잡는 방법
이 코드를 사용해 볼 수도 있습니다.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSError * error;
NSArray * directoryContents = [[NSFileManager defaultManager]
contentsOfDirectoryAtPath:documentsDirectory error:&error];
NSLog(@"directoryContents ====== %@",directoryContents);
스위프트 버전:
if let files = try? FileManager.default.contentsOfDirectory(atPath: Bundle.main.bundlePath ){
for file in files {
print(file)
}
}
디렉토리에 있는 모든 파일 나열
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
NSArray *contents = [fileManager contentsOfDirectoryAtURL:bundleURL
includingPropertiesForKeys:@[]
options:NSDirectoryEnumerationSkipsHiddenFiles
error:nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"pathExtension ENDSWITH '.png'"];
for (NSString *path in [contents filteredArrayUsingPredicate:predicate]) {
// Enumerate each .png file in directory
}
디렉토리의 파일을 재귀적으로 열거하는 중
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:bundleURL
includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey]
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:^BOOL(NSURL *url, NSError *error)
{
NSLog(@"[Error] %@ (%@)", error, url);
}];
NSMutableArray *mutableFileURLs = [NSMutableArray array];
for (NSURL *fileURL in enumerator) {
NSString *filename;
[fileURL getResourceValue:&filename forKey:NSURLNameKey error:nil];
NSNumber *isDirectory;
[fileURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];
// Skip directories with '_' prefix, for example
if ([filename hasPrefix:@"_"] && [isDirectory boolValue]) {
[enumerator skipDescendants];
continue;
}
if (![isDirectory boolValue]) {
[mutableFileURLs addObject:fileURL];
}
}
NSFileManager에 대한 자세한 내용은 여기에 있습니다.
스위프트 4:
프로젝트에 대한 상대"(파란색 폴더) 하위 항목을 사용해야 하는 경우 다음과 같이 쓸 수 있습니다.
func getAllPListFrom(_ subdir:String)->[URL]? {
guard let fURL = Bundle.main.urls(forResourcesWithExtension: "plist", subdirectory: subdir) else { return nil }
return fURL
}
용도:
if let myURLs = getAllPListFrom("myPrivateFolder/Lists") {
// your code..
}
Swift 3 (및 반환 URL)
let url = Bundle.main.resourceURL!
do {
let urls = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys:[], options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
} catch {
print(error)
}
언급URL : https://stackoverflow.com/questions/6398937/getting-a-list-of-files-in-the-resources-folder-ios
반응형
'it-source' 카테고리의 다른 글
ToMany 관계에 속하는 관련 래벨 모델에서 ID 배열을 가져옵니다. (0) | 2023.09.23 |
---|---|
워드프레스 사이트 git에서의 협업.데이터베이스를 공유하는 방법? (0) | 2023.09.23 |
행에 발생하지 않는 값 목록을 반환하는 SELECT (0) | 2023.09.18 |
도커 공유 볼륨에 대한 권한을 관리하는 가장 좋은 방법은 무엇입니까? (0) | 2023.09.18 |
CV_RETR_LIST,CV_RETR_TREE,CV_RETR_EXTER 간의 차이? (0) | 2023.09.18 |