ARQuicklook-致命错误:展开一个可选值时意外发现nil

时间:2018-09-16 19:57:31

标签: ios swift xcode quicklook

我正在跟踪this tutorial,了解如何制作AR Quicklook应用。只有几步似乎很简单。但是在最后一步,我遇到了一个致命错误,因为let变量被强制展开。我尝试将其设置为可选,但出现类似以下的错误:

  

可选链无效,表达式已经产生了“ URL?”

如果我删除了可选件,那么我会在下一行得到此警告:

  

“ URL?”不能转换为“ QLPreviewItem”;您是要使用“ as!”吗?强迫向下垂?

如果我强制展开此行,则应用程序将崩溃。我无法解决该问题。我什至都看过官方视频here,在大约14:30分钟时,他们在强制展开该行的地方也使用了相同的代码。

@IBOutlet var collectionView: UICollectionView!
let models = ["A", "B", "C", "D", "E"]

var thumbnails = [UIImage]()
var thumbnailIndex = 0

override func viewDidLoad() {
    super.viewDidLoad()
    for model in models {
        if let thumbnail = UIImage(named: "\(model).jpg") {
            thumbnails.append(thumbnail)
        }
    }

    collectionView.dataSource = self
    collectionView.delegate = self
    collectionView.reloadData()
}

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "LibraryCell", for: indexPath) as? LibraryCollectionViewCell

    if let cell = cell {
        cell.modelThumbnail.image = thumbnails[indexPath.item]
        let title = models[indexPath.item]
        cell.modelTitle.text = title.capitalized
    }

    return cell!
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    thumbnailIndex = indexPath.item

    let previewController = QLPreviewController()
    previewController.dataSource = self
    previewController.delegate = self
    present(previewController, animated: true)
}

func numberOfPreviewItems(in controller: QLPreviewController) -> Int {
    return 1
}

func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem {
    let url = Bundle.main.url(forResource: models[thumbnailIndex], withExtension: "usdz")!
    return url as QLPreviewItem
}

1 个答案:

答案 0 :(得分:1)

let url = Bundle.main.url(forResource: models[thumbnailIndex], withExtension: "usdz")!

仅当主捆绑包中不存在该项目或该项目存在但未检查目标成员资格时,才返回nil,因此请验证所有这些资源是否存在

  

A.usdz,B.usdz,C.usdz,D.usdz,E.usdz

教程制作者在这里显示了

enter image description here