ios - 使用 Swift 的 Alamofire - "Could not cast value of type ' Swift._SwiftDeferredNSArray' (ox10a75ebb0) 到 'Photomania.PhotoInfo' (0x107ee7b90)。”

标签 ios xcode swift

运行 OS X El Cap 开发测试版、iOS 9.0、Xcode 7.0 GM

我正在关注 Ray Wenderlich 教程 ( http://www.raywenderlich.com/85080/beginning-alamofire-tutorial ),但确实遇到了一些问题。在我创建请求路由器之前,我的应用程序无法运行。它构建正确,然后一旦开始加载,我就会在标题中看到调试器短语。构建错误描述为“Thread 1: signal SIGABRT”。

概述的行是:

let imageURL = (photos.objectAtIndex(indexPath.row) as! PhotoInfo).url

这是 PhotoBrowserCollectionViewController.swift 文件的完整代码。

//
//  PhotoBrowserCollectionViewController.swift
//  Photomania
//
//  Created by Essan Parto on 2014-08-20.
//  Copyright (c) 2014 Essan Parto. All rights reserved.
//

import UIKit
import Alamofire

class PhotoBrowserCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
  var photos = NSMutableOrderedSet()

  let refreshControl = UIRefreshControl()

  let PhotoBrowserCellIdentifier = "PhotoBrowserCell"
  let PhotoBrowserFooterViewIdentifier = "PhotoBrowserFooterView"

  // MARK: Life-cycle

  override func viewDidLoad() {
    super.viewDidLoad()

    setupView()

//    Alamofire.request(.GET, "https://api.500px.com/v1/photos").responseJSON() {
//        (_, _, data) in
//        print(data.value)}

    Alamofire.request(.GET, "https://api.500px.com/v1/photos", parameters: ["consumer_key": "consumer key"]).responseJSON() {
        (_,_,JSON) in
        print(JSON.value)

        let photoInfos = (JSON.value!.valueForKey("photos") as! [NSDictionary]).filter({
            ($0["nsfw"] as! Bool) == false
        }).map {
            PhotoInfo(id: $0["id"] as! Int, url: $0["image_url"] as! String)
        }

        self.photos.addObject(photoInfos)
        print(self.photos)

        self.collectionView?.reloadData()
        }
    }


  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
  }

  // MARK: CollectionView

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

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

    let imageURL = (photos.objectAtIndex(indexPath.row) as! PhotoInfo).url

    Alamofire.request(.GET, imageURL).response() {
        (_,_, data, _) in

        let image = UIImage(data: data!)
        cell.imageView.image = image
    }

    return cell
  }

  override func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
    return collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: PhotoBrowserFooterViewIdentifier, forIndexPath: indexPath) 
  }

  override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
    performSegueWithIdentifier("ShowPhoto", sender: (self.photos.objectAtIndex(indexPath.item) as! PhotoInfo).id)
  }

  // MARK: Helper

  func setupView() {
    navigationController?.setNavigationBarHidden(false, animated: true)

    let layout = UICollectionViewFlowLayout()
    let itemWidth = (view.bounds.size.width - 2) / 3
    layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
    layout.minimumInteritemSpacing = 1.0
    layout.minimumLineSpacing = 1.0
    layout.footerReferenceSize = CGSize(width: collectionView!.bounds.size.width, height: 100.0)

    collectionView!.collectionViewLayout = layout

    navigationItem.title = "Featured"

    collectionView!.registerClass(PhotoBrowserCollectionViewCell.classForCoder(), forCellWithReuseIdentifier: PhotoBrowserCellIdentifier)
    collectionView!.registerClass(PhotoBrowserCollectionViewLoadingCell.classForCoder(), forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: PhotoBrowserFooterViewIdentifier)

    refreshControl.tintColor = UIColor.whiteColor()
    refreshControl.addTarget(self, action: "handleRefresh", forControlEvents: .ValueChanged)
    collectionView!.addSubview(refreshControl)
  }

  override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "ShowPhoto" {
      (segue.destinationViewController as! PhotoViewerViewController).photoID = sender!.integerValue
      (segue.destinationViewController as! PhotoViewerViewController).hidesBottomBarWhenPushed = true
    }
  }

  func handleRefresh() {

  }
}

class PhotoBrowserCollectionViewCell: UICollectionViewCell {
  let imageView = UIImageView()

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }

  override init(frame: CGRect) {
    super.init(frame: frame)

    backgroundColor = UIColor(white: 0.1, alpha: 1.0)

    imageView.frame = bounds
    addSubview(imageView)
  }
}

class PhotoBrowserCollectionViewLoadingCell: UICollectionReusableView {
  let spinner = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)

  required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }

  override init(frame: CGRect) {
    super.init(frame: frame)

    spinner.startAnimating()
    spinner.center = self.center
    addSubview(spinner)
  }
}

最佳答案

发生这种情况是因为您使用

添加了完整的数组 photoInfos
self.photos.addObject(photoInfos)

相反你应该这样做

self.photos.addObjectsFromArray(photoInfos)

这会将 photoInfos 中的数组元素而不是整个 photoInfos 数组一个一个地添加到 photos 的索引 1 中

关于ios - 使用 Swift 的 Alamofire - "Could not cast value of type ' Swift._SwiftDeferredNSArray' (ox10a75ebb0) 到 'Photomania.PhotoInfo' (0x107ee7b90)。”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32615080/

相关文章:

ios - 如何针对不同的屏幕尺寸对齐 UITableViewCell 中的内容?

快速 avplayer Controller 获取全屏按钮

ios - Apple Mach-O 链接器与第三方 SDK 发生错误

ios - 如何在同一域的移动浏览器和 webview 之间共享数据(仅限客户端)

ios - 如何使动画 subview 中的按钮在该 subview 移动期间起作用?

ios - 为什么我的系统镜像在运行时没有显示在我的应用程序中?

ios - 更新到版本 8 后,Xcode 在 AppDelegate 中显示多个警告?

ios - ios 中长时间运行的后台任务

ios - Xcode 7.3无法将应用程序安装到iPhone

ios - 无法理解 fetchRequest.predicate