【问题标题】:save UIImage to disk with simulator ios 8 doesn't work使用模拟器 ios 8 将 UIImage 保存到磁盘不起作用
【发布时间】:2015-06-03 01:33:44
【问题描述】:

以下代码在 ios 不适用于 xcode 6.1.1 和 ios 8 设备模拟器

NSData *imageData = UIImagePNGRepresentation(shareSnapshot);
[imageData writeToFile:@"/Users/MyUser/Desktop/123.png" atomically:YES];

有人知道这是不是模拟器问题吗?我没有带 ios8 的真实设备可以检查。

【问题讨论】:

  • 你没有真实的磁盘路径。

标签: objective-c file ios8


【解决方案1】:

所以您在这里遇到了权限问题。我不确定为什么它在 8.0 之前有效,但我看到了(明显改变了):

操作无法完成。 (可可错误 513)

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/ErrorObjectsDomains/ErrorObjectsDomains.html#//apple_ref/doc/uid/TP40001806-CH202-CJBGAIBJ

就目前而言,在实际设备上运行它时会遇到问题。处理此问题的更好方法是将数据保存到应用程序的文档目录中。

  1. 通过 NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) 获取目录路径
  2. 使用 stringByAppendingPathComponent 附加文件名

然后您可以通过访问模拟器应用程序目录来验证它是否正确保存:

  • /Users/user/Library/Developer/CoreSimulator/Devices//Documents/

【讨论】:

  • 我试过了,结果是一样的,下面的 IOS 8 可以正常工作,但不能使用 IOS 8 及更高版本
  • 您肯定有写入文档目录的权限。您可能想要构建一个小型示例项目来执行此操作。随意将该示例推送到 Github,我很乐意为此进行测试。
【解决方案2】:

我记得由于安全和沙盒原因,您不能为 iOS 提供类似“/Users/MyUser/Desktop/”的路径。

退房

NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

文件以找到合适的位置

NSSearchPathDirectory 定义了很多你可以使用的路径。希望对您有所帮助

【讨论】:

    【解决方案3】:
        UIGraphicsBeginImageContext(self.frame.size);
    [self.layer renderInContext:UIGraphicsGetCurrentContext()];
    
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    // Now I use the "screenshot"
    NSString *path = [NSHomeDirectory() stringByAppendingString:@"/image.jpg"];
    if ([UIImageJPEGRepresentation(image, 1) writeToFile:path atomically:YES]) {
        NSLog(@"save ok");
    }
    else {
        NSLog(@"save failed");
    }
    

    【讨论】:

      【解决方案4】:

      试试这个。

      斯威夫特 3.0

      // Create path.
      let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
      let filePath = "\(paths[0])/MyImageName.png"
      // Save image.
      UIImagePNGRepresentation(image)?.writeToFile(filePath, atomically: true)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-08
        • 1970-01-01
        • 2013-09-09
        • 1970-01-01
        • 2021-12-04
        • 2013-09-07
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多