Jae
Jae

Reputation: 321

Image not displaying possibly due to not being saved in the file path

So I am currently trying to save an image and displaying that image in the app. However, the image is not being displayed. I'm not sure if it is due to the image not being saved correctly or some other problem. When I add the line, self.image.image = bach, the image displays correctly. However, when I comment that line out, the image does not display. But, I think, it is supposed to be displayed since I saved the data in the variable savePath. And therefore, self.image.image = UIImage(named: savePath), should cause my app to display the correct image. Any suggestions on how to fix this problem?

Here is the code:

//
//  ViewController.swift
//  Downloading An Image From The Web
//
//  Created by Jae Hyun Kim on 9/6/15.
//  Copyright © 2015 Jae Hyun Kim. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var image: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let url = NSURL(string: "http://7-themes.com/data_images/out/3/6776407-beautiful-scenery-pictures.jpg")
        let urlRequest = NSURLRequest(URL: url!)

        let task = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) -> Void in
            if error != nil {
                print(error)
            }
            else {
                if let bach = UIImage(data: data!) {
                    //self.image.image = bach
                    let documentsDirectory:String?
                    let paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentationDirectory, NSSearchPathDomainMask(), true)
                    if paths.count > 0 {
                        documentsDirectory = paths[0] as? String
                        let savePath = documentsDirectory! + "/bach.jpg"
                        NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil)
                        self.image.image = UIImage(named: savePath)
                    }
                }
            }
        })
        task!.resume()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Upvotes: 3

Views: 146

Answers (3)

Raul MPad
Raul MPad

Reputation: 41

I've had an error alike trying to use .DocumentationDirectory instead of .DocumentDirectory.

NSSearchPathForDirectoriesInDomains

method just builds the paths but doesn't check for availability|existence and you could be trying to write on an inexisting directory.

Upvotes: 0

aejhyun
aejhyun

Reputation: 612

For the line

let paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentationDirectory, NSSearchPathDomainMask, true)

you have to put NSSearchPathDomainMask.UserDomainMask. So the entire line of code should be

let paths:[AnyObject] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentationDirectory, NSSearchPathDomainMask, true)

Upvotes: 1

Leo Dabus
Leo Dabus

Reputation: 236260

The problem there is thatUIImage(named:) is for images at your resources. If you want to load your image from disk you need to use UIImage(contentsOfFile:).

Try like this:

class ViewController: UIViewController {
@IBOutlet weak var image: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        let url = NSURL(string: "http://7-themes.com/data_images/out/3/6776407-beautiful-scenery-pictures.jpg")!
        let urlRequest = NSURLRequest(URL: url)

        let task = NSURLSession.sharedSession().dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) -> Void in


            // you should always do it from the main queue otherwise you will experience a big delay when trying to display your image
            dispatch_async(dispatch_get_main_queue()) {
                // unwrap your data
                if let data = data {
                    println(data.length)
                    // get your document directory URL
                    let documentDirectory = NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true, error: nil)!
                    // create your local file url by appending your url last path component
                    let fileUrl = documentDirectory.URLByAppendingPathComponent(url.lastPathComponent!)
                    // save downloaded data to disk
                    if data.writeToURL(fileUrl, atomically: true) {
                        println(true)
                        // load your saved image from disk
                        self.image.image = UIImage(contentsOfFile: fileUrl.path!)
                    }

                }
            }

        })
        task.resume()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

Upvotes: 1

Related Questions