Swift 3.0用write编写二进制图像数据(toFile:atomically :)

时间:2016-07-05 08:13:02

标签: ios swift path uiimagepickercontroller

我正在编写教程Project10并尝试将其转换为Swift 3.0。通常直接使用 UIImagePickerController 来选择图像,然后将其保存到文档目录

我在这一行收到错误:

jpegData.write(toFile: imagePath, atomically: true)

这开始于此:

jpegData.writeToFile(imagePath, atomically: true)

错误想要用以下内容替换我的参数:

jpegData.write(to: imagePath, options: true)

我很确定这不是我想要的,无论如何它都会导致更多的字符串/ URL错误。这两种方法完全是:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    var newImage: UIImage

    if let possibleImage = info[UIImagePickerControllerEditedImage] as? UIImage {
        newImage = possibleImage
    } else if let possibleImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
        newImage = possibleImage
    } else {
        return
    }

    let imageName = NSUUID().uuidString
    let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)

    if let jpegData = UIImageJPEGRepresentation(newImage, 80) {
        jpegData.write(toFile: imagePath, atomically: true)
    }

    dismiss(animated: true, completion: nil)
}

func getDocumentsDirectory() -> NSString {
    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let documentsDirectory = paths[0]
    return documentsDirectory
}

我是否只是对Strings,NSStrings和URL感到困惑?

4 个答案:

答案 0 :(得分:4)

我在以下方面取得了一些进展:

(g,s,a) = foo([1])

g.func_code.co_freevars  # contains ('x',)
s.func_code.co_freevars  # is empty
a.func_code.co_freevars  # also empty

丑陋而且松弛可能的错误(暂时),但使用El Capitan的建议方法版本并将String转换为URL会让我前进。

答案 1 :(得分:0)

此代码适用于Swift 3:

  if let jpegData = UIImageJPEGRepresentation(iconImage!, 80) {
      do {
            try jpegData.write(to: imagePath!)

         } catch {
             print("write image failed")       
         }
   }

答案 2 :(得分:0)

if (UIImage(data: data!) != nil)
            {
                let Image = UIImage(data: data!) //image data

                self.ImageView.image = Image //Image view

                let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
                if documentsPath.count > 0{
                    let documentsDirectory = documentsPath[0]
                    let savePath = documentsDirectory + "/name.jpg"
                    do{
                        try UIImageJPEGRepresentation(Image!, 1)?.writeToURL(NSURL(fileURLWithPath: savePath), atomically: true)
                    }catch{
                        //process errors
                    }
                }
            }

您可以将手机中的图像存储在您的手机中。

答案 3 :(得分:0)

在Swift 4.1和Xcode 9.4.1中

这是完美的解决方案,我们需要使用try

do {
    try data.write(to: URL(fileURLWithPath: path), options: .atomic)
} catch {
    print(error)
}