3D Touch:在展开可选值时意外发现 nil
Posted
技术标签:
【中文标题】3D Touch:在展开可选值时意外发现 nil【英文标题】:3D Touch: unexpectedly found nil while unwrapping an Optional value 【发布时间】:2017-01-07 14:54:10 【问题描述】:为什么imageRef.data
总是nil
?我在 peek 函数中有imageRef.data
但它不属于那里?当我偷看时它会起作用(我假设图像开始下载)然后当我在 iPhone 上用力按压时,图像就会显示出来。但大多数时候我得到nil
错误。
现在,我已将该逻辑移到 pop 函数中,现在它始终是 fatal error: unexpectedly found nil while unwrapping an Optional value
import UIKit
import FirebaseStorage
extension ExpenseFeedVC: UIViewControllerPreviewingDelegate
// PEEK
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController?
guard let indexPath = tableView.indexPathForRow(at: location),
let cell = tableView.cellForRow(at: indexPath) else return nil
guard let expensePreview = storyboard?.instantiateViewController(withIdentifier: "expensePreviewVC") as? ExpensePreviewVC else return nil
expensePreview.selectedItem = expenses[indexPath.row].type
quickActionString = expenses[indexPath.row].type
let imageUrl: String = expenses[indexPath.row].receiptUrl
urlToPass = imageUrl
expensePreview.preferredContentSize = CGSize(width: 0, height: 150)
previewingContext.sourceRect = cell.frame
return expensePreview
// POP
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController)
if let rvc = storyboard?.instantiateViewController(withIdentifier: "receiptImagePreviewVC") as? ReceiptImagePreviewVC
let imageRef = FIRStorage.storage().reference(forURL: urlToPass)
imageRef.data(withMaxSize: 2*1024*1024, completion: (data, error) in
print(data!)
)
rvc.poppedImage = self.imageToPass
show(rvc, sender: self)
我把它从“偷看”中去掉了,因为如果我快速强制触摸,我会得到一个错误。如果我偷看,等待几秒钟,然后用力按压,我看到了图像。 imageRef.data
最好放在哪里,为什么 data
是 nil
(在 pop 函数内)?
urlToPass
总是返回正确的图片 url。
【问题讨论】:
【参考方案1】:异步编程的经典问题 - 下载并没有立即发生,这就是为什么它在您等待几秒钟时起作用的原因。你需要这样做:
let imageRef = FIRStorage.storage().reference(forURL: urlToPass)
imageRef.data(withMaxSize: 2*1024*1024, completion: (data, error) in
// Check for an error
...
// Prepare to switch to the next VC once the file has downloaded
rvc.poppedImage = UIImage(data: data!)
show(rvc, sender: self)
)
【讨论】:
以上是关于3D Touch:在展开可选值时意外发现 nil的主要内容,如果未能解决你的问题,请参考以下文章
Alamofire 平面错误:在展开可选值时意外发现 nil