Reputation: 231
I getting nil error. But I didnt understand why happaned. I can get selectedPhoto name with print. But I cant use in NSUrl. Could you help me pls?
my codes:
print(selectedPhoto)
if selectedPhoto != nil
{
let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(selectedPhoto)")
print("photo url: \(photoUrl)")
dataPhoto = NSData(contentsOfURL:photoUrl!)
yemekResim.image = UIImage(data: dataPhoto!)
}
else
{
print("Error")
}
Upvotes: 0
Views: 1658
Reputation: 2557
From Apples documentation on NSData(contentsOfURL)
Do not use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated.
If your app crashes because of this it will be rejected from the store.
Instead you should use NSURLSession. With the Async callback block as in my example.
Also it is not a good idea to force unwrap optionals !
as you will get run time errors instead use the if let
syntax
See my example below.
if let photo = selectedPhoto{
let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(photo)")
if let url = photoUrl{
NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {(data, response, error) in
if let d = data{
dispatch_async(dispatch_get_main_queue(), {
if let image = UIImage(data: d) {
self.yemekResim.image = image
}
})
}
}).resume()
}
}
}
Upvotes: 2
Reputation: 6140
Replace this:
let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(selectedPhoto)")
with this:
let photoUrl = NSURL(string: "http://www.kerimcaglar.com/uploads/yemek-resimler/\(selectedPhoto!)")
(Notice the "!" after selectedPhoto)
Upvotes: 0