当前位置:  开发笔记 > 编程语言 > 正文

如果响应返回200以外的状态代码,请停止我的NSURLSession?在SWIFT

如何解决《如果响应返回200以外的状态代码,请停止我的NSURLSession?在SWIFT》经验,为你挑选了1个好方法。



1> Leo Dabus..:

尝试使用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()
}

推荐阅读
帆侮听我悄悄说星星
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有