本文介绍了如何从 url 加载 UIImage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下问题:
致命错误:解包可选值时意外发现 nil
@IBOutlet weak var DetailImageView1: UIImageView!
@IBOutlet weak var DetailLabel: UILabel!
@IBOutlet weak var DetailLabel2: UILabel!
var SentData1: String!
var SentData2: String!
var SentData3: NSURL!
override func viewDidLoad() {
super.viewDidLoad()
DetailLabel.text = SentData1
DetailLabel2.text = SentData2
let url = NSURL(string: "\(SentData3)")
let data = NSData(contentsOfURL: url!)
DetailImageView1.image = UIImage(data: data!)
我正在从一个 url 中获取图片并将 url 链接从我以前的视图控制器转到这个.然后我创建了 SentData3:NSURL!现在我必须在 DetailImageView1.image 中显示图片,但是当我尝试测试应用程序时出现错误.
I am taking the picture from a url and segue the url link from my previous view controller to this one. Then I created SentData3: NSURL!Now I have to show the picture in the DetailImageView1.image, but when I try to test the app I get an error.
如果有人能告诉我错误,我会很高兴.
I would be glad if someone can show me the mistake.
推荐答案
您可以在 SwiftUI 中尝试:
You can try that for SwiftUI:
import SwiftUI
struct RemoteImage: View {
private enum LoadState {
case loading, success, failure
}
private class Loader: ObservableObject {
var data = Data()
var state = LoadState.loading
init(url: String) {
guard let parsedURL = URL(string: url) else {
fatalError("Invalid URL: \(url)")
}
URLSession.shared.dataTask(with: parsedURL) { data, response, error in
if let data = data, data.count > 0 {
self.data = data
self.state = .success
} else {
self.state = .failure
}
DispatchQueue.main.async {
self.objectWillChange.send()
}
}.resume()
}
}
@StateObject private var loader: Loader
var loading: Image
var failure: Image
var body: some View {
selectImage()
.resizable()
}
init(url: String, loading: Image = Image(systemName: "photo"), failure: Image = Image(systemName: "multiply.circle")) {
_loader = StateObject(wrappedValue: Loader(url: url))
self.loading = loading
self.failure = failure
}
private func selectImage() -> Image {
switch loader.state {
case .loading:
return loading
case .failure:
return failure
default:
if let image = UIImage(data: loader.data) {
return Image(uiImage: image)
} else {
return failure
}
}
}
}
然后在您的视图中使用它:
Then use it in your view:
struct ContentView: View {
let jsonURL = "https://cf.geekdo-images.com/thumb/img/sD_qvrzIbvfobJj0ZDAaq-TnQPs=/fit-in/200x150/pic2649952.jpg"
var body: some View {
RemoteImage(url: jsonURL)
.aspectRatio(contentMode: .fit)
.frame(width: 200)
}
}
这篇关于如何从 url 加载 UIImage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!