【问题标题】:Alamofire with Swift - "Could not cast value of type 'Swift._SwiftDeferredNSArray' (ox10a75ebb0) to 'Photomania.PhotoInfo' (0x107ee7b90)."带有 Swift 的 Alamofire -“无法将 'Swift._SwiftDeferredNSArray' (ox10a75ebb0) 类型的值转换为 'Photomania.PhotoInfo' (0x107ee7b90)。”
【发布时间】:2015-09-16 17:31:29
【问题描述】:

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

我正在关注这个 Ray Wenderlich 教程 (http://www.raywenderlich.com/85080/beginning-alamofire-tutorial),但我确实遇到了一些问题。在我创建请求路由器之前,我的应用程序无法运行。它正确构建,然后一旦开始加载,我就会得到标题中写的调试器短语。构建错误描述为“线程 1:信号 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)
  }
}

【问题讨论】:

  • 您是否调试过代码,实际上哪里出错了?在哪一行?可能有些东西没有正确连接..您正在使用的单元格,您是否在情节提要中设置了一个类?正确链接奥特莱斯?哦,要求一个新的消费者密钥,你的现在是公开的..
  • 问题实际上不在调试器指示的行中的频率?我刚刚拿了示例项目,所以所有单元格、插座、类和一切都应该是好的。还是找不到问题:S
  • 这可能是因为所有的 xcode beta 版本都发生了一些变化。我什至不得不重新添加一个文本框来修复应用程序崩溃,所以值得仔细看看“魔法”发生在哪里......

标签: ios xcode swift


【解决方案1】:

这是因为您使用

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

你应该这样做

self.photos.addObjectsFromArray(photoInfos)

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

【讨论】:

    【解决方案2】:

    我也在学习这个教程并且遇到了一些问题。首先,由于到 500px.com 服务器的网络连接不稳定,我从 JSON 数据中得到 nil,所以照片计数为 0,所以我在 UI 中看不到任何单元格;其次,我的 Xcode 的版本是 7.2 和 Swift 2.0,所以我发现我的环境发生了一些变化。如果您完全按照教程进行操作,您会遇到一些编码异常。

    self.photos.addObject(photoInfos)
    

    您应该使用函数addObjectForArray(ARRAY_NAME) 而不是addObject()。

    我不知道你的 Xcode 和 Swift 版本对我来说是否一样。我觉得编码有很多变化。所以在关于函数“响应”的闭包中,我是这样写的:

    let request = Alamofire.request(.GET, urlString, parameters: [CONSUMER_KEY : CONSUMER_KEY_VALUE])
    request.responseJSON{ response in let json = response.result.value ... }
    
    var data:NSData!
            let request = Alamofire.request(.GET, (photoMuatbleOrderedSet.objectAtIndex(indexPath.row) as! Photo).image_url!)
            request.responseData { (response) -> Void in
               data = response.data!
                let image = UIImage(data: data)
                cell.imageView.image = image
            }
            return cell
    

    随着这些变化,当应用程序运行时,我没有任何异常!

    【讨论】:

    • 嘿,我实际上已经完成了这个项目的工作,所以我不再需要这个照片问题的帮助了!都一样,感谢您的光临。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-01
    • 2016-01-12
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多