Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
144 views
in Technique[技术] by (71.8m points)

ios - Crashing when trying to pull image from URL with Swift

I am saving the image url successfully from an api and am having issues showing it when I run the app. avatarString has the correct url but as soon as I get to the next line I keep getting:

fatal error: unexpectedly found nil while unwrapping an Optional value

My avatarData var is returning as nil. I don't know what why. Running Xcode Beta 6.3. Thanks for any help.

    dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {

        var avatarString = NSURL(string: self.userInfo.avatarURL)!


        var avatarData = NSData(contentsOfURL: avatarString, options: nil, error: nil)

        var avatarImage = UIImage(data: avatarData!)

        self.avatarImage.image = avatarImage

    })
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

enter image description hereAlways do UI related work(setting ImageView image etc) in Main queue And heavy works like downloading data ,do off the main queue, try like this:

 if let avatarString = NSURL(string: self.userInfo.avatarURL) {
            dispatch_async(dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0)){

                let imageData = NSData(contentsOfURL: avatarString)
                dispatch_async(dispatch_get_main_queue()) {
                    if imageData != nil {
                        self.avatarImage?.image = UIImage(data: imageData!)

                    }
                }
            }
        }

May be it helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...