URL数组快速抛出可选错误

Posted

技术标签:

【中文标题】URL数组快速抛出可选错误【英文标题】:URL array throwing optional error swift 【发布时间】:2018-01-13 07:55:56 【问题描述】:

我不确定如何解决下面代码中“if let imageURL = imageFile.path”中出现的可选类型错误。它抛出的错误是“条件绑定的初始化程序必须具有可选类型,而不是'字符串'”

谷歌搜索后,我猜它与我在 CollectionViewController 类开头设置的 directoryContentsArray = URL 有关。

请帮忙!

附:抱歉重复的可选错误问题,但我非常困惑:/

 class CollectionViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate 

var directoryContentsArray = [URL]()

fileprivate let itemsPerRow: CGFloat = 3
fileprivate let sectionInsets = UIEdgeInsets(top: 50.0, left: 20.0, bottom: 50.0, right: 20.0)

@IBOutlet weak var collectionView: UICollectionView!  didSet 

    collectionView.delegate = self
    collectionView.dataSource = self
    


override func viewDidLoad() 
    super.viewDidLoad()

    func fetchDirectoryContents() 
        let fileManager = FileManager.default
        let documentDirectory = fileManager.urls(for: .documentDirectory, in: .userDomainMask)[0]
        let directoryContents = try! fileManager.contentsOfDirectory(at: documentDirectory, includingPropertiesForKeys: nil)

        self.directoryContentsArray = directoryContents
        self.collectionView.reloadData()
    

    checkPhotoLibraryPermission()



override func viewDidAppear(_ animated: Bool) 
    super.viewDidAppear(animated)
    self.collectionView.reloadData()


//number of views
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int 

    return directoryContentsArray.count
        

//populate the views
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? myCell 
        let imageFile = self.directoryContentsArray[indexPath.item]
            if let imageURL = imageFile.path,
                imageFile.pathExtension == "jpeg",
                let image = UIImage(contentsOfFile: imageURL) 
                    cell.myImageView.image = image
                 else 
            fatalError("Can't create image from file \(imageFile)")
        
        return cell
    
    return UICollectionViewCell()


func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) 

if let imageURL = info[UIImagePickerControllerImageURL] as? URL 

    let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    do 
        try FileManager.default.moveItem(at: imageURL.standardizedFileURL, to: documentDirectory.appendingPathComponent(imageURL.lastPathComponent))
        collectionView.reloadData()
     catch 
        print(error)
    


picker.dismiss(animated: true, completion: nil)

再次感谢!

【问题讨论】:

【参考方案1】:

URL的path属性定义为:

var path: String

所以它不会返回一个可选项,这意味着您不需要进行 let 赋值。

改成这样:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell 

    if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as? myCell 
        let imageFile = self.directoryContentsArray[indexPath.item]
            if imageFile.pathExtension == "jpeg",
                let image = UIImage(contentsOfFile: imageFile.path) 
                    cell.myImageView.image = image
                 else 
            fatalError("Can't create image from file \(imageFile)")
        
       return cell
    
    return UICollectionViewCell()

【讨论】:

以上是关于URL数组快速抛出可选错误的主要内容,如果未能解决你的问题,请参考以下文章

NSString 到 String 抛出“致命错误:在展开可选值时意外发现 nil”

AVFoundation 快速播放声音 2

drawRect 在 Xcode 游乐场抛出“致命错误:在展开可选值时意外发现 nil”

快速获取条件绑定的错误初始化程序必须具有可选类型,为啥?

快速致命错误:在展开可选值时意外发现 nil

json数据快速返回nil