尝试使用guard来解包你的选项并添加where子句来控制预期的结果,如果失败只返回nil:
func loadData() { downloadFullImageFrom("https://www.google.fr/logos/doodles/2015/holidays-2015-day-3-6399865393250304-5649050225344512-ror.jpg") { image in dispatch_async(dispatch_get_main_queue()) { guard let image = image else { print("error loading image") return } //DO SOMETHING WITH images IF DOWNLOAD IS OK print(image.size) } } } func downloadFullImageFrom(link: String, completion: ((image: UIImage?) -> Void)) { guard let url = NSURL(string: link) else { completion(image: nil) return } NSURLSession.sharedSession().dataTaskWithURL(url) {(data, response , error) in guard let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200, let data = data, image = UIImage(data: data) where error == nil else { // display a network issue pop up print("======= statusCode =======") print((response as? NSHTTPURLResponse)?.statusCode) completion(image: nil) return } completion(image: image) }.resume() }
Xcode 8.3.1•Swift 3.1
func loadData() { downloadFullImageFrom(link: "https://www.google.fr/logos/doodles/2015/holidays-2015-day-3-6399865393250304-5649050225344512-ror.jpg") { image in DispatchQueue.main.async() { guard let image = image else { print("error loading image") return } //DO SOMETHING WITH images IF DOWNLOAD IS OK print(image.size) } } } func downloadFullImageFrom(link: String, completion: @escaping ((UIImage?) -> Void)) { guard let url = URL(string: link) else { completion(nil) return } URLSession.shared.dataTask(with: url) { data, response, error in guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let data = data, let image = UIImage(data: data), error == nil else { // display a network issue pop up print("======= statusCode =======") print((response as? HTTPURLResponse)?.statusCode ?? "") completion(nil) return } completion(image) }.resume() }