iphone存储以及读取指定文件(Documents)中的内容

本文介绍如何在iOS应用中使用Objective-C进行图片的存储、读取及操作,包括保存图片到Documents目录、从Documents目录中读取图片、删除图片等功能,并提供实际代码示例。
有时需要把一些资料保存在沙盒Documents或其下的新建文件夹中

存储

if (image!=nil) 
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
	//以model.itemid image.png为区分保存在Documents中
	NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"image%d.png",model.itemid]];
	BOOL result = [UIImagePNGRepresentation(image) writeToFile:uniquePath atomically:YES];
	if (result)
	{
	  UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"" message:@"图片保存成功!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
	  [alert show];
	  [alert release];
	} else {
		UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"" message:@"图片保存失败!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
		[alert show];
		[alert release];
	}  
}

取值

NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDir error:nil];
//所有png图片存在一个Array数组中
NSArray *onlyPics = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.png'"]];
couponMyViewController.pageArray = onlyPics; //传值到下一个Controller中

操作

NSString *operate = [actionSheet buttonTitleAtIndex:buttonIndex];
if ([operate isEqualToString:@"删除优惠券"]) 
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[pageArray objectAtIndex:pageTag]];
    BOOL succeed = [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];


    if (succeed) 
    {
			UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"" message:@"图片删除成功!" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
			[alert show];
			[alert release];
			[navigation popViewControllerAnimated:YES];  
    }
}
else if ([operate isEqualToString:@"保存到相册"])
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    NSString *documentDir = [paths objectAtIndex:0];
    NSString *imgPath=[documentDir stringByAppendingPathComponent:[pageArray objectAtIndex:pageTag]];
    UIImage *img=[UIImage imageWithContentsOfFile:imgPath];
    UIImageWriteToSavedPhotosAlbum(img, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
}


- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo 
{
    if (error != NULL)
    {
    }
    else  // No errors
    {
			[self saveSucceed];
    }
}


- (void)saveSucceed 
{
    UIAlertView *sucAlert = [[UIAlertView alloc] initWithTitle:@"" message:@"图片已保存到相册" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [sucAlert show];
    [sucAlert release];
    self.navigationItem.leftBarButtonItem.enabled = YES;
    self.navigationItem.rightBarButtonItem.enabled = YES;
}

另外:UIimageView 读取图片的时候,

1、NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
  NSString *imgPath=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"bgimage.png"];
  NSData *data=[NSData dataWithContentsOfFile:imgPath];    
  UIImage *img=[UIImage imageWithData:data]; 
       
2、NSString *imgPath=[documentDir stringByAppendingPathComponent:@“dhhddjaskhfk.png”];
  UIImage *img=[UIImage imageWithContentsOfFile:imgPath];  
  
3、UIImage *img=[UIImage imageWithName:XXX];
  
4、读取URL图片
   NSURL *url = [NSURL URLWithString:@"http://xxx.jpg"];   
   NSData *urlData = [NSData dataWithContentsOfURL:url];
   UIImage *image = [UIImage imageWithData:urlData];

Documents的根目录

#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] 
#define FILEPATH [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]

通过下面这段代码,就可以获取一个目录内的文件及文件夹列表。

NSFileManager *fileManager = [NSFileManager defaultManager];
//在这里获取应用程序Documents文件夹里的文件及文件夹列表
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDir = [documentPaths objectAtIndex:0];
NSError *error = nil;
NSArray *fileList = [[NSArray alloc] init];
//fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
fileList = [fileManager contentsOfDirectoryAtPath:documentDir error:&error];

以下这段代码则可以列出给定一个文件夹里的所有子文件夹名

NSMutableArray *dirArray = [[NSMutableArray alloc] init];
BOOL isDir = NO;
//在上面那段程序中获得的fileList中列出文件夹名
for (NSString *file in fileList) 
{
	NSString *path = [documentDir stringByAppendingPathComponent:file];
	[fileManager fileExistsAtPath:path isDirectory:(&isDir)];
	if (isDir) 
	{
		[dirArray addObject:file];
	}
	isDir = NO;
}
NSLog(@"Every Thing in the dir:%@",fileList);
NSLog(@"All folders:%@",dirArray);

下面的对图片的处理

//从照片库中选取照片
-(void) selectImage
{
    UIImagePickerController *picker=[[UIImagePickerController alloc]init];
    picker.delegate=self;
    picker.allowsImageEditing=YES;
    //UIImagePickerControllerSourceTypePhotoLibrary,// 相片库
    //UIImagePickerControllerSourceTypeCamera// 相机获取图片
    //UIImagePickerControllerSourceTypeSavedPhotosAlbum// 这个是自定义库,是由用户截图或保存到里面的
    picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentModalViewController:picker animated:YES];
    [picker release];
}
-(void) saveImage
{
  if (myImageView.image!=nil) 
  {
	//此处首先指定了图片存取路径(默认写到应用程序沙盒 中)
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
	//并给文件起个文件名
	NSString *uniquePath=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"bgimage.png"];

	//此处的方法是将图片写到Documents文件中 如果写入成功会弹出一个警告框,提示图片保存成功
	BOOL result=[UIImagePNGRepresentation(myImageView.image)writeToFile: uniquePath    atomically:YES];

	if (result)
	{
	   UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Tip message" message:@"save sucess!" delegate:nil cancelButtonTitle:@"Enter" otherButtonTitles:nil];
	   [alert show];
	   [alert release];
	}
   } 
   else
   {
	UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Tip message" message:@"Please select a picture!" delegate:nil cancelButtonTitle:@"Enter" otherButtonTitles:nil];
	[alert show];
	[alert release];
   }
}

-(void)setBackgroundImage:(UIImage *)img;
{
	//拿到应用程序沙盒里面的路径
  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
	//读取存在沙盒里面的文件图片
  NSString *imgPath=[[paths objectAtIndex:0] stringByAppendingPathComponent:@"bgimage.png"];
	//因为拿到的是个路径 把它加载成一个data对象
  NSData *data=[NSData dataWithContentsOfFile:imgPath];    
  //直接把该 图片读出来
  UIImage *img=[UIImage imageWithData:data];    
  CGRect imageRect=CGRectMake(0.0, 0.0, 320.0, 460.0);
  UIImageView *customBackground = [[UIImageView alloc] initWithFrame:imageRect];
  customBackground.image=img;
  [self.view insertSubview:customBackground atIndex:1];
  [customBackground setClipsToBounds:YES];
  [customBackground setContentMode:UIViewContentModeScaleToFill];
  [customBackground release];
  [img release];
}

从Documents中选择全部png图片

NSString *documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDir error:nil];
NSArray *onlyPics = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"self ENDSWITH '.png'"]];

从Documents中删除一项

1、以删除air.mp4为例:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
NSString *documentsDirectory = [paths objectAtIndex:0]; 
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"air.mp4"];
BOOL succeed = [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];

2、有提示
NSFileManager *fileMgr = [[[NSFileManager alloc] init] autorelease];
NSError *error = nil;
NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
if (error == nil) 
{
	for (NSString *path in directoryContents) 
	{
		NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
		BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
		if (!removeSuccess) 
		{
			// Error handling
			...
		}
	}
} 
else 
{
	// Error handling
	...
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值