App沙盒和iTunes File Share

背景

iOS中app是基于一个沙盒来读写数据的,这是Apple的安全策略,今天我们就来简要学习一下这个sandbox和相关的文件读写操作。
我们还是跟着一个demo来学习,最后将会演示一下如何看到app内的文件。

Demo

1.首先还是新建一个single application project,命名为iTunesFileShareDemo。

新建iTunesFileShareDemo

2.下面讲述最简单的文件读写,app的沙盒里面有三个目录,分别是Documents,Library和tmp,之后的的文件读写我们都在Documents这个目录下。
获取Documents路径的方法如下:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];

NSDocumentDirectory是一个数组,而且只有一个元素,通过第二行代码我们取出了Documents路径。

3.写入沙盒的代码非常简单,我使用了最简洁的形式。

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    
    //获取document路径
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    
    //文件名及其路径
    NSString *fileName = @"test.txt";
    NSString *filePath = [documentDirectory stringByAppendingPathComponent:fileName];
    
    //建立一个char数组,并归档写入到沙盒中
    char *a = "hello, world";
    NSData *data = [NSData dataWithBytes:a length:12];
    [data writeToFile:filePath atomically:YES];
}

以上操作会把"hello, world"进行归档,然后写入到沙盒中的Documents路径下的test.txt文件中。
4.那么如何验证文件被正确写入了呢?这里有个非常直观的方法,通过iTunes来查看app沙盒中的数据。
在project的配置选项的Info中添加一个Application supports iTunes file sharing选项,并且设定值为YES。这样就能允许iTunes来访问分享的文件了。

Application supports iTunes file sharing

5.发开iTunes,点击应用中我们的iTunesFileShareDemo,可以看到有一个test.txt文件。

沙盒中的test.txt文件

6.将其拖拽出来,打开可以看到文本正确写入了内容"hello, world"。

文本内容"hello, world"

总结

以上简要说明了iOSapp沙盒的目录结构,并演示了读写方法,最后还可视化地给出了一个通过iTunes访问沙盒数据的方法。
感谢您的阅读,大家的支持是我不断更新的动力。
这篇文章对您有帮助,欢迎转载,请注明出处。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容