From: :https://www.cnblogs.com/8335IT/p/8436236.html
背景
现象
发现mac程序,Mac 上 fopen总返回NULL,无法写文件;提示错误为:Operation no permitted.
原因
mac应用开着沙盒。去掉沙盒,打开文件成功。
开沙盒下,进一步尝试
1.全局、相对路径都不行、在沙盒中获取也不行.
//在沙盒中获取Documents的完整路径
NSString * path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
//得到path下test文件的路径
NSString * filePath = [path stringByAppendingPathComponent:@"test"];
//判断test文件是否存在
NSFileManager * fm = [NSFileManager defaultManager];
if ([fm fileExistsAtPath:filePath]) {
NSLog(@"test文件存在");
}else{
NSLog(@"test文件不存在");
}
2.写文件的时候,bundle路径打开文件又出错了.
NSBundle *mainBundle = [NSBundle mainBundle];
NSString *imagePath = [mainBundle pathForResource:@"abc" ofType:@"png"];
在build PHASE 的copy bundle resource中将要播放的文件添加,然后,
fopen([文件指针,utf8...],"rb")
Mac Sandbox
为了提高系统安全性,苹果引入了Sandbox机制,要在app store发布的软件需符合该机制。
软件的读写权限被严格的限制在一定范围内,大部分路径的读写权限需要向用户请求。
但是有些数据我们需要获得较高的权限,而且没必要每次都向用户申请。如何解决呢?
还好apple给我们留了一个路径让我们自由读写。下面是apple文档介绍如何操作相应目录
The app container directory. Upon first launch, the operating system
creates a special directory for use by your app—and only by your
app—called a container. Each user on a system gets an individual
container for your app, within their home directory; your app has
unfettered read/write access to the container for the user who ran it.
写文件使用NShomedirectory();
NSString *path = nshomedirectory();
path = [path stringbyappendingstring:@"文件名"];
file *FPATH = fopen([path utf8string] ,"wb");
到时候去 finder下 commend shift g, 然后~/library 下找到保存的写文件。
网友评论