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

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

下面的对图片的处理
//从照片库中选取照片
-(IBAction) 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];
}
-(IBAction) 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
    ...
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
款已经超过额度,请尽快还款。 | 垃圾 | | 你好,您的快递已经在Qt读取和解析JSON文件可以使用Qt自带的QJsonDocument类和QJsonObject类。下面是一个到达,请尽快领取。 | 正常 | | 您好,恭喜您获得iPhone手机一台,请点击简单的例子: ```c++ // 读取JSON文件 QString jsonFilePath = "path/to/json/file.json"; QFile链接领取。 | 垃圾 | | 你好,我们公司正在招聘前端设计师,请尽快申请。 jsonFile(jsonFilePath); if (!jsonFile.open(QIODevice::ReadOnly | QIODevice::Text)) { qDebug() << "Failed to open | 正常 | | 你好,我们公司正在招聘后端设计师,请尽快申请。 | 正常 JSON file:" << jsonFilePath; return; } // 解析JSON文本 QJsonParseError parseError; QJsonDocument json | | 你好,我们公司正在招聘UI设计师,请尽快申请。 | 正常 | | 您好,Doc = QJsonDocument::fromJson(jsonFile.readAll(), &parseError); if (parseError.error != QJsonParseError::NoError) { qDebug() << "Failed to parse JSON file:" << parseError.errorString(); return; } // 获取JSON对象 Q您的信用卡已经欠款10万元,请尽快还款。 | 垃圾 | | 你好,您的JsonObject jsonObj = jsonDoc.object(); // 获取JSON的数据 QString name = jsonObj["name"].toString(); int age = jsonObj["age快递已经到达,请查收。 | 正常 | | 您好,恭喜您获得iPhone手机一台,请"].toInt(); bool married = jsonObj["married"].toBool(); ``` 在这个例子,我们首先打开JSON文件回电确认。 | 垃圾 | | 你好,我们公司正在招聘大数据设计师,请尽快申请。,然后使用`QJsonDocument::fromJson()`函数将JSON文本解析为`QJsonDocument`对象。如果解析 | 正常 | | 你好,我们公司正在招聘人工智能设计师,请尽快申请。 |失败,我们可以使用`QJsonParseError`类获取错误信息。 接着,我们可以使用`QJsonDocument::object()`函数获取JSON对象,并使用`[]`运算符获取其的数据。需要注意的是,如果JSON的数据类型与 正常 | | 你好,我们公司正在招聘机器学习设计师,请尽快申请。 | 正常我们获取的类型不匹配,会发生运行时错误。因此,在实际应用,我们应该先 | | 您好,您的信用卡欠款已经超过额度,请尽快还款。 | 垃圾 | 检查JSON数据的类型再进行转换。 希望这个例子能够帮助你理解如何在Qt读取和解析JSON文件

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值