IOS检测指定路径的文件是否存在
程序员文章站
2022-03-02 15:07:13
复制代码 代码如下:
- (nsstring *)datapath:(nsstring *)file
{
&nbs...
复制代码 代码如下:
- (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];
//此处首先指定了图片存取路径(默认写到应用程序沙盒 中)
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];
}
检查文件是否存在
复制代码 代码如下:
nsstring *path = [[nsbundle mainbundle] pathforresource:filename oftype:@""];
if(path==null)
方法二:
复制代码 代码如下:
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");
}
方法三:
复制代码 代码如下:
//判断文件是否存在
if(![c judgefileexist:@"user.plist"])
{
nslog(@"请确认该文件是否存在!");
return;
}
方法四:
复制代码 代码如下:
//判断文件是否存在
-(bool)judgefileexist:(nsstring * )filename
{
//获取文件路径
nsstring *path = [[nsbundle mainbundle] pathforresource:filename oftype:@""];
if(path==null)
return no;
returnyes;
}
上一篇: IOS 改变键盘颜色代码
下一篇: CDR怎么使用调和工具设计惊艳的图标?