ios - 当你发出网络请求并且它没有带来图像时如何设置默认图像?

标签 ios json xcode swift networking

所以我正在发出网络请求。我将 JSON 解析为自定义对象。在这些对象中,有一些 url 应该可以带回图像。其中一个 URL 返回一条错误消息 (404),因此那里什么都没有!如何在其位置设置默认图像并阻止我的应用程序崩溃?这是我的代码!谢谢

import UIKit

class HomepageCollectionViewController: UICollectionViewController {

    var imageCache = NSCache()
    var hingeImagesArray = [HingeImage]()
    var arrayToHoldConvertedUrlToUIImages = [UIImage]()
    var task: NSURLSessionDataTask?

    override func viewDidLoad() {
        super.viewDidLoad()

        // Makes the network call for HingeImages
        refreshItems()
    }

    override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return 1
    }

    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return hingeImagesArray.count
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier("imageReuseCell", forIndexPath: indexPath) as! ImageCollectionViewCell

        let image = hingeImagesArray[indexPath.row]

        if let imageURL = image.imageUrl {

            if let url = NSURL(string: imageURL) {

                //settingImageTpChache

                if let myImage = imageCache.objectForKey(image.imageUrl!) as? UIImage {

                    cell.collectionViewImage.image = myImage

                }else {

                 // Request images asynchronously so the collection view does not slow down/lag
                self.task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in

                        // Check if there is data returned
                        guard let data = data else {
                            return
                        }

                        // Create an image object from our data and assign it to cell


                        if let hingeImage = UIImage(data: data){

                            //cachedImage
                          self.imageCache.setObject(hingeImage, forKey: image.imageUrl!)


                           dispatch_async(dispatch_get_main_queue(), { () -> Void in

                           cell.collectionViewImage.image = hingeImage

                            //append converted Images to array so we can send them over to next view - only proble in that the only images converted at the ones you scrool to which is retarted

                            self.arrayToHoldConvertedUrlToUIImages.append(hingeImage)

                            print(self.arrayToHoldConvertedUrlToUIImages)

                             })


                        }
                })

                task?.resume()

                      }
            }
        }

        return cell
    }

最佳答案

您可以检查错误是否不为零,然后设置默认图像。

self.task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) -> Void in

if error != nil { 
 cell.collectionViewImage.image = UIImage(named:"default_image")
 return 
}
...

关于ios - 当你发出网络请求并且它没有带来图像时如何设置默认图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36686081/

相关文章:

iOS 扩展和受限 API

iphone - 点击 tabBar 时转到 rootView

json - 描述请求和返回数据的 REST API 响应

javascript - 如何根据我从ajax获得的json在select上添加禁用的select属性

ios - 隐藏奇怪的不需要的 Xcode 日志

ios - CMAltitudeData 最后有一些奇怪的数据,有什么想法吗?

objective-c - UIButton 有间隙

ios - 无法在我的 Mac OS X 终端中导航目录。我得到 “No such file or directory”

ios - 如何从 NSDictionary 的 NSArray 获取 Unique NSDictionary

json - kafka connect中按某个值过滤记录