iOS 沙盒机制

iOS沙盒:笼统的说就是APP的文件目录系统。

一:简介

1是iOS安全机制,每个iOS程序只能访问自己沙盒中的东西

2是对程序执行各种操作的权限限制

3访问其他APP沙盒,需要权限。

4非代码文件都在此保存,例如图片,图标,视频,plist文件,文本文件。

5APP之间不能相通,只能通过URL scheme来通信。

6相对独立,封闭。


二:访问路径:1)/Users/XXXXX/Library/Developer/CoreSimulator/

2).通过finder逐步查找

三:沙盒内部三个文件:

1 documents:保存应用运行时生成的需要持久化的数据,iTunes会自动备份该目录。
苹果建议将在应用程序中浏览到的文件数据保存在该目录下

2 temp:存放临时文件,例如访问地理位置弹框,网络授权弹框等,每次卸载APP都会删除。

3 library:下边是有Caches,Preferences

 
 
Caches: 一般存储的是缓存文件,例如图片视频等,此目录下的文件不会再应用程序退出时删除。 *在手机备份的时候,iTunes不会备份该目录。 例如音频,视频等文件存放其中 Preferences: 保存应用程序的所有偏好设置iOS的Settings(设置),我们不应该直接在这里创建文件, 而是需要通过NSUserDefault这个类来访问应用程序的偏好设置。 *iTunes会自动备份该文件目录下的内容。 比如说:是否允许访问图片,是否允许访问地理位置......

4 .app:就是APP包


四:

 
 

1).获取沙盒的Home目录 //获取根目录 NSString homePath = NSHomeDirectory(); NSLog(@"Home目录:%@",homePath); 2).获取沙盒的Documents目录 / 获取Documents文件夹目录, @param NSDocumentDirectory 获取Document目录 @param NSUserDomainMask 是在当前沙盒范围内查找 @param YES 展开路径,NO是不展开 @return test.txt文件的路径 / NSString filePath =[[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES)firstObject]stringByAppendingPathComponent:@"test.txt"]; 3).获取Library文件路径 / * 获取Library目录下文件路径 * * @param NSLibraryDirectory 获取Library目录 * @param NSUserDomainMask 在当前的沙盒范围内查找 * @param YES 展开路径,NO不展开路径 * * @return test.txt文件的路径 / NSString filePath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"test.txt"]; 4).获取Library/Caches文件目录 / * 获取Library目录下文件路径 * * @param NSCachesDirectory 获取Library/Caches目录 * @param NSUserDomainMask 在当前的沙盒范围内查找 * @param YES 展开路径,NO不展开路径 * * @return test.txt文件的路径 /NSString filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"test.txt"]; 5).获取Library/Preferences文件目录 Preferences由系统维护,不需要我们手动的获取文件路径进行操作,而是需要借助NSUserDefault来操作,但是我们是可以获取到这个文件的。 / * 获取Library目录下文件路径 * * @param NSLibraryDirectory 获取Library目录 * @param NSUserDomainMask 在当前的沙盒范围内查找 * @param YES 展开路径,NO不展开路径 * * @return test.txt文件的路径 / NSString filePath = [[NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"Preferences"]; 6).获取tmp文件路径 / * 获取tmp文件目录下的文件路径 * * @return test.txt的文件路径 */ NSString *filePath = [NSTemporaryDirectory()stringByAppendingPathComponent:@"test.txt"] 7).向沙盒中写入文件 //向沙盒中写入文件 NSString *documentsPathW = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0]; //写入文件 if (!documentsPathW) { NSLog(@"目录未找到"); }else { NSString *filePaht = [documentsPath stringByAppendingPathComponent:@"test.txt"]; NSArray *array = [NSArray arrayWithObjects:@"code",@"change", @"world", @"OK", @"", @"是的", nil]; [array writeToFile:filePaht atomically:YES];} 8).向沙盒中读取文件 //从沙盒中读取文件 NSString *documentsPathR = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES)[0]; NSString *readPath = [documentsPathR stringByAppendingPathComponent:@"test.txt"]; NSArray *fileContent = [[NSArray alloc] initWithContentsOfFile:readPath]; NSLog(@"文件内容:%@",fileContent);

  • 3.代码获取应用程序包的目录与内容

1).获取应用程序包的路径 NSString *imagePath = [NSBundle mainBundle].resourcePath; -- 程序包文件,包含了资源文件和可执行文件AppName.app 2).获取程序包中一个图片资源路径的方法(apple.png) NSString *imagePath = [[NSBundle mainBundle]pathForResource:@"apple" ofType:@"png"]; 注意: 1.imageWithname这种加载的方式的是有缓存的,第二次在加载时直接从内存中取出图片, 这样的话效率更高,但是会使得内存变得越来越大,通常使用在,图片内存较小, 而且需要频繁使用的地方。 2.NSBundle mainBundle 是通过获取图片的全路径来加载图片的, 不会有缓存,但是这样每次就得重新加载,它也不会是在不是在使用完图片后就释放, 而是在下一次使用图片的时候才会释放,所以需要我们在使用完图片后,手动来释放内存。 3).将NSData类型的数据存储到本地(以图片为例)

下边是一个例子:

我们项目中遇到的,loading页加一个gif图,我们是把后台返回的gif链接,下载到本地沙盒,下次取出来。但是比后台晚一次。

下载:

#pragma mark - 本地loading图

- (void)requstLoadingGifFromServer {

    [API2 getLoadingImageHandler:^(NSDictionary *dic, NSError *error) {

        if (!error) {

            NSString *url = dic[@"img_url"];

            if (url.length == 0) {

                return;

            }

            

            dispatch_queue_t globalQueue = dispatch_get_global_queue(0, 0);

            dispatch_async(globalQueue, ^{

                NSString *prefix = @"loadingImagePathKeyPrefix";

                

                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

                NSString *baseCachePath = [paths objectAtIndex:0];

                NSString *filePath = [NSString stringWithFormat:@"%@/LoadingImg",baseCachePath];

                

                // 判断LoadingImg文件夹是否存在,如果不存在,则创建

                if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {

                    [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];

                } else {

                    NSLog(@"LoadingImg document is exists=%@",filePath);

                }

                

                NSString *newUrl = [url stringByReplacingOccurrencesOfString:@"/" withString:@"_"];

                NSString *urlValue = [[NSUserDefaults standardUserDefaults] valueForKey:newUrl];

                //对比本地缓存url和服务器url

                if (![newUrl isEqualToString:urlValue]) {

                    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];

                    UIImage *image = [UIImage imageWithData:imageData];

                    

                    //缓存到cache

                    NSString *defaultPath = [NSString stringWithFormat:@"/%@",newUrl];

                    NSString *imagePath = [filePath stringByAppendingPathComponent:defaultPath];

                    BOOL success = [imageData writeToFile:imagePath atomically:YES];

                    if (success) {

                        NSLog(@"LoadingImg图片缓存成功");

                    }

                    

                    //存url和path

                    [[NSUserDefaults standardUserDefaults] setValue:defaultPath forKey:loadingPathLastPath];

                    [[NSUserDefaults standardUserDefaults] setValue:newUrl forKey:newUrl];

                    [[NSUserDefaults standardUserDefaults] setValue:defaultPath forKey:[NSString stringWithFormat:@"%@%@",prefix,newUrl]];

                    NSLog(@"---path=%@",defaultPath);

                    

                }else { //更新lastPath路径

                    NSString *imagePath = [[NSUserDefaults standardUserDefaults] valueForKey:[NSString stringWithFormat:@"%@%@",prefix,newUrl]];

                    [[NSUserDefaults standardUserDefaults] setValue:imagePath forKey:loadingPathLastPath];

                    NSLog(@"---path=%@",imagePath);

                }

            });

        }

    }];

}



展示:

// 读取gif图片数据:上次缓存的图片

- (UIImageView *)getGifImage{

    NSString *cachePath = [[NSUserDefaults standardUserDefaults]valueForKey:loadingPathLastPath];

    UIImage *theBacImg = nil;

    NSData *data11;

    if (cachePath != nil){

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

        NSString *filePath = [NSString stringWithFormat:@"%@/LoadingImg",[paths objectAtIndex:0]];

        NSString *path = [NSString stringWithFormat:@"%@%@",filePath,cachePath];

        data11 = [NSData dataWithContentsOfFile:path];

        

//        UIImage *img = [UIImage imageWithData:data];

//        NSLog(@"得到的图片路径=%@==图片=%@",path,img);

//

//        theBacImg = img ?:[UIImage imageNamed:@"loadingGif"];

    }else {

        theBacImg = [UIImage imageNamed:@"loadingGif"];

    }

    

//    NSURL *fileUrl = [[NSBundle mainBundle] URLForResource:@"loadingGif" withExtension:@"gif"];

//    CGImageSourceRef gifSource = CGImageSourceCreateWithURL((CFURLRef) fileUrl, NULL);

//    size_t frameCout = CGImageSourceGetCount(gifSource);

//    NSMutableArray *images = [[NSMutableArray alloc] init];

//    for (size_t i = 0; i < frameCout; i++) {

//        CGImageRef imageRef = CGImageSourceCreateImageAtIndex(gifSource, i, NULL);

//        UIImage *imageName = [UIImage imageWithCGImage:imageRef];

//        [images addObject:imageName];

//        CGImageRelease(imageRef);

//    }

//    UIImage *img = images.firstObject;

    UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, QNTopHeight, SCREEN_WIDTH, SCREEN_HEIGHT - QNTopHeight)];

    gifImageView.backgroundColor = [UIColor whiteColor];

//    gifImageView.animationImages = images;

//    gifImageView.animationDuration = 2;

//    [gifImageView startAnimating];

//    gifImageView.contentMode = UIViewContentModeScaleAspectFit;

    

//    [gifImageView sd_animatedGIFWithData: data11];

    UIImage *img = [UIImage sd_animatedGIFWithData:data11];

    gifImageView.image = img;

    return gifImageView;

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值