Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - NSURL error

Tags:

ios

swift

nsurl

Getting an error when trying to use the NSURL class below, the code below is essentially trying to store an image I am pulling in from Facebook into an imageView. The error is as follows:

value of optional type 'NSURL?' not unwrapped, did you mean to use '!' or '?' 

Not sure why this is is happening, help!

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var myImage: UIImageView!

    override func viewDidLoad() {

        super.viewDidLoad()

        let myProfilePictureURL = NSURL(string: "http://graph.facebook.com/bobdylan/picture")
        let imageData = NSData(contentsOfURL: myProfilePictureURL)
        self.myImage.image = UIImage(data: imageData)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
like image 906
Dan Riaz Avatar asked Oct 30 '14 17:10

Dan Riaz


People also ask

What is Nsurl domain?

An object representing the location of a resource that bridges to URL ; use NSURL when you need reference semantics or other Foundation-specific behavior.

What causes Nsurlerrorcancelled?

A requested resource couldn't be retrieved. An attempt to establish a secure connection failed for reasons that can't be expressed more specifically. A server certificate is expired, or is not yet valid. A server certificate wasn't signed by any root server.

How do I fix Nsurlerrordomain error 1012?

You might see this error message if you are running an outdated version of the NetUpdate application on your Mac. To resolve the issue, simply download and install the latest version of NetUpdate. Now, restart your computer and NetUpdate should work again as expected.

What is made up of NSError object?

The core attributes of an NSError object are an error domain (represented by a string), a domain-specific error code and a user info dictionary containing application specific information.


Video Answer


1 Answers

The NSURL constructor you're calling has got this signature:

convenience init?(string URLString: String)

? means that the constructor may not return a value, hence it is considered as an optional.

Same goes for the NSData constructor:

init?(contentsOfURL url: NSURL)

A quick fix is:

let myProfilePictureURL = NSURL(string: "http://graph.facebook.com/bobdylan/picture")
let imageData = NSData(contentsOfURL: myProfilePictureURL!)
self.myImage.image = UIImage(data: imageData!)

The best solution is to check (unwrap) those optionals, even if you're sure that they contain a value!

You can find more infos on optionals here: link to official Apple documentation.

like image 87
Matteo Pacini Avatar answered Oct 17 '22 23:10

Matteo Pacini