How to convert code objective c to Swift to save image?

后端 未结 5 1384
别跟我提以往
别跟我提以往 2021-01-11 18:24

I have seen this code in other post, for save pictures:

  // Create path.
 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,      NSU         


        
5条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-11 18:50

    As follows:

    let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
    let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
    if let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true) {
        if paths.count > 0 {
            if let dirPath = paths[0] as? String {
                let readPath = dirPath.stringByAppendingPathComponent("Image.png")
                let image = UIImage(named: readPath)
                let writePath = dirPath.stringByAppendingPathComponent("Image2.png") 
                UIImagePNGRepresentation(image).writeToFile(writePath, atomically: true)
            }
        }
    }
    

    "paths" is an AnyObject[], so you have to check that its elements can be converted to String.

    Naturally, you wouldn't actually use "NSDocumentDirectory" as the name, I just did it for clarity.

    Update for Xcode 7.2

    NSSearchPathForDirectoriesInDomains now returns [String] rather than [AnyObject]? so use

    let nsDocumentDirectory = NSSearchPathDirectory.DocumentDirectory
    let nsUserDomainMask = NSSearchPathDomainMask.UserDomainMask
    let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
    if let dirPath = paths.first {
        // ...
    }
    

    The fact that .stringByAppendingPathComponent is also deprecated is dealt with in this answer...

提交回复
热议问题