在 App 裡做快取、離線檔案或圖片懶載入時,「這個檔案已經存在於本機了嗎?」幾乎是必寫的判斷。以下整理幾種常見的檢查方式。
先把常用的取路徑邏輯抽成方法,順便確保資料夾已經建立,後續存檔就不用擔心路徑不存在:
- (NSString *)dataPath:(NSString *)file
{
NSString *path = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]
stringByAppendingPathComponent:@"badge"];
BOOL bo = [[NSFileManager defaultManager] createDirectoryAtPath:path
withIntermediateDirectories:YES
attributes:nil
error:nil];
NSAssert(bo, @"創建目錄失敗");
NSString *result = [path stringByAppendingPathComponent:file];
return result;
}
這是最實戰的場景:先檢查本地有沒有檔案,有就直接讀,沒有才走網路下載並寫入沙盒:
- (void)viewDidLoad
{
[super viewDidLoad];
// 指定存取路徑,預設寫入 App 沙盒的 Documents 目錄
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
// 建立子目錄
NSString *imageDir = [[[paths objectAtIndex:0] stringByAppendingPathComponent:@"163"]
stringByAppendingPathComponent:@"songzi"];
// 完整檔案路徑
NSString *imagePath = [imageDir stringByAppendingPathComponent:@"文件名.png"];
NSData *data = nil;
// 檢查圖片是否已存在於本地
if ([self isExistsFile:imagePath]) {
data = [NSData dataWithContentsOfFile:imagePath];
} else {
data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"網址"]];
// 建立資料夾
[[NSFileManager defaultManager] createDirectoryAtPath:imageDir
withIntermediateDirectories:YES
attributes:nil
error:nil];
// 寫入圖片
[UIImagePNGRepresentation([UIImage imageWithData:data])
writeToFile:imagePath atomically:YES];
}
imageView.image = [UIImage imageWithData:data];
}
如果目標是打包在 .app 內的資源,用 NSBundle 取路徑,取不到就代表不存在:
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@""];
if (path == NULL) {
// 檔案不存在
}
這是最直接、也最推薦的寫法,一行就能判斷:
NSFileManager *fileManager = [NSFileManager defaultManager];
// 取得 Documents 目錄
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
if ([fileManager fileExistsAtPath:@""] == YES) {
NSLog(@"File exists");
}
呼叫端先攔一次,語意更清楚:
// 使用前先確認檔案存在
if (![c judgeFileExist:@"user.plist"]) {
NSLog(@"請確認該檔案是否存在!");
return;
}
// 判斷 bundle 中的檔案是否存在
- (BOOL)judgeFileExist:(NSString *)fileName
{
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@""];
if (path == NULL) {
return NO;
}
return YES;
}
沙盒內的檔案一律用 fileExistsAtPath: 判斷最省事;bundle 內的資源則透過 pathForResource:ofType: 間接判斷。另外要注意,寫檔前務必先確保上層目錄存在,這一步偷懶很容易導致寫入靜默失敗。