Reputation: 2494
Im trying to load images from a URL on Swift, and instantiate it. I can compile my code, but it breaks when I compile the code.
this is my class code:
class Beer {
let name : String
let beernameInDB : String
let imgUrl : NSURL
var err : NSError?
let imageData : NSData
let img : UIImage
init(name : String, imgUrl: String, beernameInDB : String){
self.name = name
self.imgUrl = NSURL.URLWithString(imgUrl);
self.beernameInDB = beernameInDB
self.imageData = NSData.dataWithContentsOfURL(self.imgUrl,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
self.img = UIImage(data: imageData)
}
}
And here is where I instantiate, and it breaks:
class FirstViewController: UIViewController {
var array = [
Beer(name: "Budweiser", imgUrl: "https://s3.amazonaws.com/brewerydbapi/beer/1P45iR/upl[ad_upBR4q-large.png", beernameInDB:"Anheuser-Busch InBev-Budweiser")
]
When i run it, it breaks on this line of the class:
self.imageData = NSData.dataWithContentsOfURL(self.imgUrl,options: NSDataReadingOptions.DataReadingMappedIfSafe, error: &err)
With the message "fatal error: unexpectedly found nil while unwrapping an Optional value"
Essentially, I think its probably trying to assign a value to imageData before imgUrl is defined, so I tried changed that line to have 'NSURL.URLWithString(imgUrl)' instead of 'self.imgUrl', but it didn't fix, so I don't really know what is the problem right now
Upvotes: 1
Views: 295
Reputation: 19524
This is a different technique but here is some simple code to load a web photo:
import UIKit
import WebKit
class ViewController: UIViewController {
@IBOutlet var containerView : UIView?
var webView: WKWebView?
override func loadView() {
super.loadView()
self.webView = WKWebView()
self.view = self.webView!
}
override func viewDidLoad() {
super.viewDidLoad()
var url = NSURL(string:"http://chart.finance.yahoo.com/z?s=AAPL&t=6m&q=l&l=on&z=s&p=m50,m200")
var req = NSURLRequest(URL:url)
self.webView!.loadRequest(req)
}
}
Upvotes: 1