URL array throwing optional error swift

岁酱吖の 提交于 2020-01-06 07:14:00

问题


I am not sure how to resolve the optional type error that occurs at "if let imageURL = imageFile.path" in my code below. The error it throws is "Initializer for conditional binding must have Optional type, not 'String'"

After googling, I'm guessing it has something to do with the directoryContentsArray = URL I set at the beginning of my CollectionViewController class.

Please help!

P.S. Sorry for the repeat optional error question, but I'm super confused :/

 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)
}

Thanks again!


回答1:


The definition of the path property of URL is:

var path: String

So it doesn't return an optional which means you don't need to do the let assignment.

Just change to this:

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()
}


来源:https://stackoverflow.com/questions/48238003/url-array-throwing-optional-error-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!