swift - 在 Swift 中检索远程照片时,如何防止由于连接速度慢而导致应用程序崩溃或卡住?

标签 swift

我想通过 url 字符串在我的表格 View 单元格中显示头像图像。当手机没有连接到互联网时它会崩溃,所以我给它添加了 Reachability swift 。但现在我面临另一个问题,当用户离开 wifi 区域或互联网连接不稳定时,应用程序将卡住,直到我走回强 wifi 区域,我才能点击任何东西。为什么?

let imageData:NSData = try! NSData(contentsOf: imageUrl)

此代码会崩溃,所以我尝试添加 do & catch 但仍然无法正常工作。是不是因为应用无法连接到url字符串并获取数据,所以应用会被卡住?如何防止在检索远程照片时由于连接速度慢而导致应用程序崩溃或卡住?

if Reachability.shared.isConnectedToNetwork(){
    if let crew = user!["crew"] as? [String:Any], let crewAva = crew["crew_avatar"] as? String {
        let imageUrlString = crewAva
        let imageUrl:URL = URL(string: imageUrlString)!

        DispatchQueue.main.async(execute:  {
            do{
                let imageData:NSData = try NSData(contentsOf: imageUrl)
                let image = UIImage(data: imageData as Data)
                self.avaImg.image = image
            }
            catch{
                print("error")
            }
        })
    }
}else{
    print("Not reachable")
}

最佳答案

来自NSData documentation :

init?(contentsOf url: URL)

Important

Don't use this synchronous method to request network-based URLs. For network-based URLs, this method can block the current thread for tens of seconds on a slow network, resulting in a poor user experience, and in iOS, may cause your app to be terminated. Instead, for non-file URLs, consider using the dataTask(with:completionHandler:) method of the NSURLSession class. See URL Session Programming Guide for details.

关于swift - 在 Swift 中检索远程照片时,如何防止由于连接速度慢而导致应用程序崩溃或卡住?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46825446/

相关文章:

swift - 使用 RPScreenRecorder 开始捕获保存屏幕录制

swift - 如何在 Xcode 11/Swift 5.1 中使用 Swift Package Manager 创建动态框架(像 Carthage 那样)?

ios - UISearchController/UINavigationBar 在 UINavigationController 中使用时显示损坏的动画

swift - 通知中心或关闭?

ios - Swift - 使用哪些类型? NSString 或字符串

ios - 如何在 iOS 10 上使用 CallKit 显示来电显示(添加标识条目)

swift - 播放声音文件时启动时出现白屏 SKAction

ios - 使 UITextView 高度动态化,约束乘数问题

swift - 为什么导入 Vapor 时会出现 Swift 编译器错误?

swift - 如何在知道字符数但不知道字节数的情况下解码 UTF-8?