我有以下问题:
致命错误:在解包可选值时意外发现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!)
我正在从网址中获取图片并将我之前的视图控制器中的网址链接转换为此链接。然后我创建了SentData3:NSURL! 现在我必须在DetailImageView1.image中显示图片,但是当我尝试测试应用程序时出现错误。
如果有人能证明我的错误,我会很高兴。
答案 0 :(得分:1)
您可以为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
}
}
}
}
然后在您的视图中使用它:
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)
}
}
答案 1 :(得分:0)
如果SentData3已经是一个URL,您只需插入即可。当你不确定它是否会返回nil时,不要强行打开一个变量。
if let imageData: NSData = NSData(contentsOfURL: SentData3) {
DetailImageView1.image = UIImage(data: imageData)
}
答案 2 :(得分:0)
这对我有用...
var image: UIImage?
let urlString = "https://example.com/filename"
let url = NSURL(string: urlString)! as URL
if let imageData: NSData = NSData(contentsOf: url) {
image = UIImage(data: imageData as Data)
}
...“图像”,如果出现错误将为nil,或者将包含新的UIImage对象。