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

有时需要把一些资料保存在沙盒Documents或其下的新建文件夹中
存储
    if(image!=nil){        
       NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
       NSString *uniquePath=[[paths objectAtIndex:0]stringByAppendingPathComponent:[NSStringstringWithFormat:@"image%d.png",model.itemid]];//以
model.itemidimage.png为区分保存在Documents中
       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:[NSPredicatepredicateWithFormat:@"self ENDSWITH '.png'"]];

couponMyViewController.pageArray = onlyPics;//传值到下一个Controller中
操作
       NSString *operate = [actionSheetbuttonTitleAtIndex:buttonIndex];
       if ([operate isEqualToString:@"删除优惠券"]) {
           NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES); 
           NSString *documentsDirectory = [pathsobjectAtIndex:0]; 
           NSString *filePath = [documentsDirectorystringByAppendingPathComponent:[pageArrayobjectAtIndex: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];
               [navigationpopViewControllerAnimated:YES];  

           }
       }else if ([operate isEqualToString:@"保存到相册"]) {
           NSArray *paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
           NSString *documentDir = [paths objectAtIndex:0];
           NSString *imgPath=[documentDirstringByAppendingPathComponent:[pageArrayobjectAtIndex: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];
    [sucAlertshow];
    [sucAlertrelease];
   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=[NSDatadataWithContentsOfFile:imgPath];    
    UIImage*img=[UIImageimageWithData:data];    

2、NSString *imgPath=[documentDirstringByAppendingPathComponent:@“dhhddjaskhfk.png”];
     UIImage *img=[UIImageimageWithContentsOfFile:imgPath];  
3、 UIImage *img=[UIImageimageWithName:XXX];  

4、读取URL图片
    NSURL *url =[NSURLURLWithString:@"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 = [NSFileManagerdefaultManager];
//在这里获取应用程序Documents文件夹里的文件及文件夹列表
       NSArray *documentPaths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
       NSString *documentDir = [documentPaths objectAtIndex:0];
       NSError *error = nil;
       NSArray *fileList = [[NSArray alloc] init];
//fileList便是包含有该文件夹下所有文件的文件名及文件夹名的数组
       fileList = [fileManager contentsOfDirectoryAtPath:documentDirerror:&error];

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

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

下面的对图片的处理
//从照片库中选取照片
-(IBAction) selectImage{
    UIImagePickerController*picker=[[UIImagePickerController alloc]init];
    picker.delegate=self;
    picker.allowsImageEditing=YES;
    //UIImagePickerControllerSourceTypePhotoLibrary,//相片库
    //UIImagePickerControllerSourceTypeCamera//相机获取图片
    //UIImagePickerControllerSourceTypeSavedPhotosAlbum//这个是自定义库,是由用户截图或保存到里面的
    picker.sourceType=UIImagePickerControllerSourceTypePhotoLibrary;
    [selfpresentModalViewController:picker animated:YES];
    [pickerrelease];
}
-(IBAction) saveImage{
    if(myImageView.image!=nil) 
    {
        //此处首先指定了图片存取路径(默认写到应用程序沙盒中)
        NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        //并给文件起个文件名
        NSString*uniquePath=[[paths objectAtIndex:0]stringByAppendingPathComponent:@"bgimage.png"];
        
        //此处的方法是将图片写到Documents文件中如果写入成功会弹出一个警告框,提示图片保存成功
        BOOLresult=[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];
            [alertshow];
            [alertrelease];
               
        
    }else{
        UIAlertView*alert=[[UIAlertView alloc]initWithTitle:@"Tip message"message:@"Please select a picture!" delegate:nilcancelButtonTitle:@"Enter" otherButtonTitles:nil];
        [alertshow];
        [alertrelease];
    }

}

-(void)setBackgroundImage:(UIImage *)img;
{
//拿到应用程序沙盒里面的路径
    NSArray*paths =NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
//读取存在沙盒里面的文件图片
    NSString*imgPath=[[paths objectAtIndex:0]stringByAppendingPathComponent:@"bgimage.png"];
//因为拿到的是个路径 把它加载成一个data对象
    NSData*data=[NSDatadataWithContentsOfFile:imgPath];    
    //直接把该图片读出来
    UIImage*img=[UIImageimageWithData:data];    
    CGRectimageRect=CGRectMake(0.0, 0.0, 320.0, 460.0);
    UIImageView*customBackground = [[UIImageView alloc]initWithFrame:imageRect];
    customBackground.image=img;        
    [self.viewinsertSubview:customBackground atIndex:1];
    [customBackgroundsetClipsToBounds:YES];
    [customBackgroundsetContentMode:UIViewContentModeScaleToFill];
    [customBackgroundrelease];
    [imgrelease];
}
从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
    ...
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值