我想通过 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")
}
最佳答案
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 theNSURLSession
class. See URL Session Programming Guide for details.
关于swift - 在 Swift 中检索远程照片时,如何防止由于连接速度慢而导致应用程序崩溃或卡住?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46825446/