ARQuicklook - 致命错误:在展开Optional值时意外发现nil

问题描述 投票:0回答:1

我关注如何制作AR Quicklook应用程序的this tutorial。只有几个步骤似乎很简单。然而,在最后一步,我得到一个致命的错误,因为让变量被强行打开。我试过让它成为一个可选项,但我得到了不同的错误:

可选链没有效果,表达式已经产生'URL?'

如果我删除了可选的I,那么请在下一行中收到此警告:

“网址是什么?”不能转换为'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
}
ios swift xcode quicklook
1个回答
1
投票

这个

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

如果该项目在主Bundle中不存在,则只能返回nil,或者存在但不检查目标成员资格,因此请验证所有这些资源是否存在

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

教程制作者在这里显示

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.