IOS檢測指定路徑的文件是否存在
更新時間:2015年05月27日 10:06:13 投稿:hebedich
本文給大家分享的是在IOS開發(fā)中檢測指定文件是否存在的方法,給大家匯總了4種,十分實用,小伙伴們根據(jù)自己的需求自由選擇吧。
復(fù)制代碼 代碼如下:
- (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,@"創(chuàng)建目錄失敗");
NSString *result = [path stringByAppendingPathComponent:file];
return result;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//此處首先指定了圖片存取路徑(默認(rèn)寫到應(yīng)用程序沙盒 中)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
//并給文件起個文件名
NSString *imageDir = [[[paths objectAtIndex:0] stringByAppendingPathComponent:@"163"] stringByAppendingPathComponent:@"songzi"];
//存放圖片的文件夾
NSString *imagePath =[imageDir stringByAppendingPathComponent:@"文件名.png"];
NSData *data = nil;
//檢查圖片是否已經(jīng)保存到本地
if([self isExistsFile:imagePath]){
data=[NSData dataWithContentsOfFile:imagePath];
}else{
data = [NSData dataWithContentsOfURL:[NSURL URLWithString: @"網(wǎng)址"]];
//創(chuàng)建文件夾路徑
[[NSFileManager defaultManager] createDirectoryAtPath:imageDir withIntermediateDirectories:YES attributes:nil error:nil];
//創(chuàng)建圖片
[UIImagePNGRepresentation([UIImage imageWithData:data]) writeToFile:imagePath atomically:YES];
}
imageView.image = [UIImage imageWithData:data];
}
檢查文件是否存在
復(fù)制代碼 代碼如下:
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@""];
if(path==NULL)
方法二:
復(fù)制代碼 代碼如下:
NSFileManager *fileManager = [NSFileManager defaultManager];
//Get documents directory
NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
if ([fileManager fileExistsAtPath:@""]==YES) {
NSLog(@"File exists");
}
方法三:
復(fù)制代碼 代碼如下:
//判斷文件是否存在
if(![c judgeFileExist:@"user.plist"])
{
NSLog(@"請確認(rèn)該文件是否存在!");
return;
}
方法四:
復(fù)制代碼 代碼如下:
//判斷文件是否存在
-(BOOL)judgeFileExist:(NSString * )fileName
{
//獲取文件路徑
NSString *path = [[NSBundle mainBundle] pathForResource:fileName ofType:@""];
if(path==NULL)
return NO;
returnYES;
}
相關(guān)文章
Objective-C的NSOperation多線程類基本使用指南
這篇文章主要介紹了Objective-C的NSOperation多線程類基本使用指南,談到了Operations的執(zhí)行順序和并發(fā)量等設(shè)置操作,需要的朋友可以參考下2016-02-02iOS 中使用tableView實現(xiàn)右滑顯示選擇功能
這篇文章主要介紹了iOS 中使用tableView實現(xiàn)右滑顯示選擇功能的相關(guān)資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2016-07-07iOS CoreMotion實現(xiàn)設(shè)備運動加速度計陀螺儀
這篇文章主要介紹了iOS CoreMotion實現(xiàn)設(shè)備運動加速度計陀螺儀,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-12-12iOS 導(dǎo)航欄無縫圓滑的隱藏 Navigationbar實例代碼
本文通過實例代碼給大家介紹了iOS 導(dǎo)航欄無縫圓滑的隱藏 Navigationbar的效果,代碼簡單易懂,非常不錯,具有參考借鑒價值,需要的朋友可以參考下2017-11-11Apple?Watch?App?Lifecycle應(yīng)用開發(fā)
這篇文章主要為大家介紹了Apple?Watch?App?Lifecycle應(yīng)用開發(fā)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-10-10