简体   繁体   中英

ContentsOfURL returns nil in swift 2.0 from a perfectly valid URL

I am trying to fetch an image from a URL but the contentsOfURL method keeps returning nil. The url is legal and has only one image. I have tried the dispatch_get_global_queue method and also the method described below. The NSData value is always nil no matter how many times i run. i have already tried restarting the simulator as well. The network is also fast and there are no issues with the network. This is the part of the code that is failing

var imageURL : NSURL(string : "https://www.nasa.gov/sites/default/files/wave_earth_mosaic_3.jpg")

if let url = imageURL{
        spinner?.startAnimating()
        let request = NSURLRequest(URL: url)
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request){(data,response,error) -> Void in
            self.imageData = NSData(contentsOfURL: url)
        }
            dispatch_async(dispatch_get_main_queue()){
                if url == self.imageURL{
                    self.image = UIImage(data: self.imageData!)
                }
                else{

                }
        }
        task.resume()
    }

This is how your function should look like. No need for GCD. There is also no need for let task = .... and NSData(contentsOfURL: url) downloads the image again as Eric D stated.

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        var imageURL = "https://www.nasa.gov/sites/default/files/wave_earth_mosaic_3.jpg"

        loadImage(fromUrl: imageURL) { (image, error) in
            if let image = image {
                print("got an image")
            } else {
                print("got an error")
            }
        }
    }

    // pretty function that takes a string and a callback
    // it sends either an image or an error back through the callback
    func loadImage(fromUrl urlString: String, completion:(image:UIImage?,error:NSError?) -> Void) {

        guard let url = NSURL(string:urlString) else {
            // invalid url
            completion(image: nil,error: nil)
            return
        }

        let request = NSURLRequest(URL: url)
        NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) in

            if let error = error {
                completion(image: nil,error: error)
                return
            }

            guard let data = data, image = UIImage(data:data) else {
                // no connection error, but no image extracted from data
                return completion(image: nil, error: nil)
            }

            completion(image: image, error: nil)
        }.resume()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM