【问题标题】:URL array throwing optional error swiftURL数组快速抛出可选错误
【发布时间】: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)
}

再次感谢!

【问题讨论】:

    标签: arrays swift url uicollectionview optional


    【解决方案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()
    }
    

    【讨论】:

      猜你喜欢
      • 2017-06-20
      • 2012-05-05
      • 2018-01-06
      • 1970-01-01
      • 2015-10-14
      • 1970-01-01
      • 2021-03-24
      • 2018-06-08
      • 2018-04-27
      相关资源
      最近更新 更多