ios - 尝试使用 URLsession 从 DataTask 创建图像无效

标签 ios swift

我创建了一个函数,该函数将从 url 获取图像并将其分配给一个变量,然后它将该变量作为图像返回。虽然它没有返回任何东西并且崩溃了。

func downloadImage(imageUrl:String) -> UIImage {
        var imageDownloaded : UIImage?
        let configuration = URLSessionConfiguration.default
        let session = URLSession(configuration: configuration)
        let task = session.dataTask(with: URL(string: imageUrl)!) { (data, response, error) in
            if error != nil {
                return
            }
            do {
                imageDownloaded = try UIImage(data: data!)
            } catch {
                print("Fail")
            }
        }
        task.resume()
        return imageDownloaded! //Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
    }

最佳答案

您正试图在变量“imageDownloaded”没有任何值(即 nil)时强行展开它。这是因为下载图像数据需要时间。

要解决这个问题,您应该使用完成处理程序

func downloadImage(imageUrl:String, @escaping completionHandler: (UIImage?)->()) {
    var imageDownloaded : UIImage?
    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration)
    let task = session.dataTask(with: URL(string: imageUrl)!) { (data, response, error) in
        if error != nil {
            return
        }
        do {
            imageDownloaded = try UIImage(data: data!)
            completionHandler(imageDownloaded!)
        } catch {
            print("Fail")
            completionHandler(nil)
        }
    }
    task.resume()
}

关于ios - 尝试使用 URLsession 从 DataTask 创建图像无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58903141/

相关文章:

ios - 从用户位置查找数组中最近的经度和纬度 - iOS Swift

ios - 使用按钮以编程方式更改方向 - iOS

swift - 附加到数组的元素返回 nil

swift 4 : Cannot call value of non-function type '[Self.Element.Type]' when instantiating associated type array

android - 在 IOS 和 Android 上 react native fbsdk 用户更改问题

objective-c - ios - UIActivityIndi​​catorView 是否应该默认显示?

iphone - 如何将sqlite3数据库文件存放在应用程序的Library目录下?

ios - 使用标题单元格时不考虑 UICollectionView 的sectionInsets

ios - [React Native][IOS] 如何通过通知打开应用程序时捕获事件

ios - 如何将 nil 类型传递给 Swift 中的参数?