0

I am using swift and cloudkit trying to fetch images from cloudserver as below and I am getting error: "initializer of conditional binding must have optional type not CKAsset" at the line: if let ckAsset = image { please help as I am new to swift and this is my first app

 let ckRecord = Saveddata[indexPath.row]
    weak var weakCell = cell
    backgroundQueue.addOperation {
        let image = ckRecord.object(forKey: "Photos") as! CKAsset

        if let ckAsset = image {
            if let URL = ckAsset.fileURL {
            let imagedata = NSData(contentsOf: URL)
            OperationQueue.main.addOperation() {
                cell.imageView?.image = UIImage(data: imagedata! as Data)
                }

        }

        }
rania
  • 57
  • 7
  • whenever you use `if let` the right hand of the `=` should be an*optional*. However `image` is NOT and an optional. Because: in the line before you forced unwrapped image using `as! CKAsset` – mfaani Feb 01 '17 at 22:49
  • so HOw can I execute same logic with forcing image to be CKAsset – rania Feb 01 '17 at 22:51
  • If you get that error: Don't use `if let`. Just use `let`.though it's best to use `guard` instead of the whole forced unwrapping – mfaani Feb 01 '17 at 22:53
  • To use guard see [here](http://stackoverflow.com/q/32256834/5175709) – mfaani Feb 01 '17 at 22:57

1 Answers1

1

I think what you're looking for is this:

let ckRecord = Saveddata[indexPath.row]
weak var weakCell = cell
backgroundQueue.addOperation {
    let image = ckRecord.object(forKey: "Photos")

    // Conditionally cast image resource
    if let ckAsset = image as? CKAsset {
        // This isn't optional, no protection needed
        let url = ckAsset.fileURL

        // Data(contentsOf:...) will throw on failure
        do {
            // Fetch the image data (try because it can fail and will throw if it does)
            let imagedata = try Data(contentsOf: url)
            OperationQueue.main.addOperation() {
                weakCell?.imageView?.image = UIImage(data: imagedata)
            }
        }
        catch {
            // handle data fetch error
        }
    }
}

It conditionally casts the resource as a CKAsset and only proceeds if it actually is one.

David Berry
  • 40,941
  • 12
  • 84
  • 95