3

I need realy, realy help

I save Image in to DocumentDirectory how to take this Image and put in to UIImageView?

photo url:

file:///Users/zoop/Library/Developer/CoreSimulator/Devices/3E9FA5C0-3III-41D3-A6D7-A25FF3424351/data/Containers/Data/Application/7C4D9316-5EB7-4A70-82DC-E76C654EA201/Documents/profileImage.png

Vykintas
  • 401
  • 1
  • 8
  • 23

3 Answers3

7

Try something like that:

let fileName = "profileImage.png"
let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first! + "/" + fileName
let image = UIImage(contentsOfFile: path)

Then you can put image to UIImageView.

Other option (as Leo Dabus mentioned in comments bellow):

let fileName = "profileImage.png"
let fileURL = NSURL(fileURLWithPath: NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!).URLByAppendingPathComponent(fileName)
if let imageData = NSData(contentsOfURL: fileURL) {
    let image = UIImage(data: imageData) // Here you can attach image to UIImageView
}
0

You can use NSFileManager's method URLsForDirectory to get the document directory url and URLByAppendingPathComponent to append the file name to the original url:

if let fileURL = NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first?.URLByAppendingPathComponent("profileImage.png"),
    // get the data from the resulting url
    let imageData = NSData(contentsOfURL: fileURL),
    // initialise your image object with the image data
    let image = UIImage(data: imageData) {
    print(image.size)
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
-1

In Swift 4.2:

func getImageFromDirectory (_ imageName: String) -> UIImage? {

    if let fileURL = FileManager().urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("\(imageName).png") {
        // get the data from the resulting url
        var imageData : Data?
        do {
             imageData = try Data(contentsOf: fileURL)
        } catch {
            print(error.localizedDescription)
            return nil
        }
        guard let dataOfImage = imageData else { return nil }
        guard let image = UIImage(data: dataOfImage) else { return nil }
        return image
    }
    return nil
}
Zakaria
  • 1,040
  • 3
  • 13
  • 28
Carmine Cuofano
  • 191
  • 1
  • 3