讀取快取或本地存檔前,先確認檔案在不在,可以避免不必要的網路請求,也能防止 dataWithContentsOfFile 回 nil 造成的後續崩潰。以下是完整的實作脈絡。
- (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, @"創建目錄失敗");
return [path stringByAppendingPathComponent:file];
}
- (void)viewDidLoad {
[super viewDidLoad];
// 指定圖片存取路徑(寫入 App 沙盒)
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 bundle 內的資源(唯讀,不可寫入):
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@""];
if (path == NULL) { /* 資源不存在 */ }
用 NSFileManager 檢查沙盒檔案:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
if ([fileManager fileExistsAtPath:@""] == YES) {
NSLog(@"File exists");
}
封裝成一個判斷方法,呼叫端更乾淨:
// 判斷 bundle 中的資源是否存在
-(BOOL)judgeFileExist:(NSString *)fileName {
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@""];
if (path == NULL) return NO;
return YES;
}
// 使用
if (![c judgeFileExist:@"user.plist"]) {
NSLog(@"請確認該文件是否存在!");
return;
}
實務上建議把「取得目錄 → 組出路徑 → 檢查存在 → 讀取或下載」這段邏輯收攏到一個方法裡,避免路徑字串散落在各處。另外要注意,pathForResource:ofType: 的 type 若傳空字串,檔名必須含副檔名;傳 @"plist" 則檔名不要帶副檔名,這是最常見的誤用來源。若只是要判斷 bundle 資源存在與否,用 [[NSBundle mainBundle] pathForResource:...] 回傳 nil 即可,不必再包一層 NSFileManager。