简体   繁体   中英

requestImageForAsset always returns nil - even after checking for nil

So, I'm having a weird (and frustrating) issue. I'm looping through an array of assets returned by an image picker:

let manager = PHImageManager.defaultManager()
let options = PHImageRequestOptions()
for asset in assets {
    var image = UIImageView?
    manager.requestImageForAsset(asset, targetSize: CGSize(width: asset.pixelWidth, height: asset.pixelHeight), contentMode: .AspectFit, options: option, resultHandler: { (result, info) -> Void in
        if result == nil {
            print("Nil alert!")
            return
        }
        print("not nil")
        image!.image = result

    }
}

In the console I get the expected messages:

not nil

immediately followed by this message:

fatal error: unexpectedly found nil while unwrapping an Optional value

I've been messing around with this for hours and I can't seem to figure out what exactly the problem is. If I try to print the result directly it says something like <UIImage: 0x12f780a20>, {45, 60}

Any help would be welcome :)

You aren't setting anything to image after defining it, so it's going to be nil here:

 var image = UIImageView?

When you force-unwrap it with ! here, you're hitting the runtime error:

 image!.image = result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM