简体   繁体   English

UIImage下载返回零和崩溃的应用程序(快速)

[英]UIImage Download Returning nil and Crashing App (Swift)

I have an image url string: 我有一个图片网址字符串:

var remoteImage: String = "http://server.com/wall-e.jpg"

I then construct a UIImage to download on a separate thread using Grand Central Dispatch with remoteImage as the NSURL string parameter: 然后,我使用Grand Central Dispatch构造一个UIImage以在单独的线程上下载,并将remoteImage作为NSURL字符串参数:

let getImage = UIImage(data: NSData(contentsOfURL: NSURL(string: remoteImage)!)!)

When it is finished and I return back to the main thread, I have it save internally: 完成后,我返回主线程,将其保存在内部:

UIImageJPEGRepresentation(getImage, 1.0).writeToFile(imagePath, atomically: true)

On Wi-fi and LTE it downloads fine, but when testing edge cases such as on an Edge network (no pun intended), I inconsistently get the error: 在Wi-fi和LTE上,它可以正常下载,但是在测试边缘情况(例如在边缘网络上(无双关))时,我不一致地收到错误消息:

fatal error: unexpectedly found nil while unwrapping an Optional value

Now I thought I would be safe by making sure that it wasn't nil by adding in: 现在,我想通过添加以下内容确保它不会nil将是安全的:

if getImage != nil { ... }

But it didn't seem to make a difference. 但这似乎没有什么不同。 It still gets the error and highlights the let getImage as written above. 它仍然会收到错误,并突出显示如上所述的let getImage What am I doing wrong here? 我在这里做错了什么? Should I be checking nil in a different manner or method? 我应该以其他方式或方法检查nil吗?

I would recommend you to use AsyncRequest to fetch and download the image and saved it locally. 我建议您使用AsyncRequest来获取和下载图像并将其保存在本地。 As you didn't posted any of code of your problem. 由于您没有发布任何问题代码。 So i am posting a sample working for me. 因此,我正在发布为我工作的示例。

Sample for downloading and saving image locally 用于本地下载和保存图像的样本

    var url = NSURL(string : "http://freedwallpaper.com/wp-content/uploads/2014/09/Tattoo-Girl.jpg")

    let urlrequest = NSURLRequest(URL: url!)
    NSURLConnection.sendAsynchronousRequest(urlrequest, queue: NSOperationQueue.mainQueue(), completionHandler: {
        response ,data , error in

        if error != nil
        {
            println("error occurs")
        }
        else
        {
            let image = UIImage(data: data)

            /* Storing image locally */

            var documentsDirectory:String?
            var paths = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
            println(paths)
            if paths.count > 0{
                documentsDirectory = paths[0] as? String
                var savePath = documentsDirectory! + "/bach.jpg"
                NSFileManager.defaultManager().createFileAtPath(savePath, contents: data, attributes: nil)
                self.bach.image  = UIImage(named: savePath)
            }
        }

    })

}

The error, does, in fact lie on the line: 实际上,该错误确实存在:

    let getImage = UIImage(data: NSData(contentsOfURL: NSURL(string: remoteImage)!)!)

The reason is that it's not the UIImage that is initially returning nil, it is probably NSData returning nil. 原因是最初返回nil的不是UIImage,可能是NSData返回nil。 You could check if NSData is returning nil, and then create the UIImage object instead. 您可以检查NSData是否返回nil,然后创建UIImage对象。

EDIT: What the particular line of code is doing is it is assuming that NSData is always returning a non-nil value, which may not be true when you are not connected. 编辑:特定代码行在做的是假设NSData始终返回非零值,当您未连接时这可能不正确。 When you're not connected, it gets a nil value, which you are trying to say will never be a nil value using the exclamation mark (!). 当您未连接时,它将获得一个nil值,您尝试使用感叹号(!)将该值永远设为nil值。

I suggest you read further on how Swift works. 我建议您进一步阅读Swift的工作原理。 For this particular example, take a look at what the exclamation marks actually mean in Swift: What does an exclamation mark mean in the Swift language? 对于此特定示例,请看一下感叹号在Swift中的实际含义: 感叹号在Swift语言中是什么意思?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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