场景: 我希望能够通过@Published值(networkMessage和hasAlert)从Observable对象显示Alert()。
缺少网络连接时应触发此警报。
通过
here
主机视图,其中显示Alert():
import SwiftUI
struct EndPointView: View {
@EnvironmentObject var settings: Settings
@ObservedObject var standardWeatherReport = StandardWeatherReport()
@ObservedObject var publishedWeatherReport = PublishedWeatherReport()
@ObservedObject var pepBoy = PepBoy()
@ObservedObject var postMan = PostMan()
var body: some View {
Form {
Text("Chosen One: \(settings.endpointSection)")
Text("Row Two")
Text("Row Three")
Text("Row Four")
}.onAppear {
self.acquireData()
}
.alert(isPresented: $standardWeatherReport.hasAlert, content: { () -> Alert in
Alert(title: Text(verbatim: standardWeatherReport.networkMessage!))
})
}
func acquireData() {
let chosenEndPoint = EndPoints(rawValue: settings.endpointSection)
switch chosenEndPoint {
case .standardWeather:
standardWeatherReport.doStandard()
case .publishedWeather:
publishedWeatherReport.doPublish()
case .postman:
postMan.doPublishPostMan()
case .publishpepboy:
pepBoy.doPublishPep()
case .none:
print("none")
}
}
}
可观察对象最初通过case .failure(让anError)触发了Alert():
import Foundation
class PublishedWeatherReport: ObservableObject {
@Published var networkMessage: String?
@Published var hasAlert = false
@Published var weatherReport: String?
func doPublish() {
let url = EndPoint.weather.path()
var request = URLRequest(url: EndPoint.weather.path()!)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
// Publisher:
let remoteDataPublisher = URLSession.shared.dataTaskPublisher(for: url!)
// the dataTaskPublisher output combination is (data: Data, response: URLResponse)
.map { $0.data }
.decode(type: Sample.self, decoder: decoder)
.receive(on: DispatchQueue.main)
.eraseToAnyPublisher()
// Subscriber:
sub = remoteDataPublisher // ...must assign to an iVar to keep alive.
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
break
case .failure(let anError):
self.networkMessage = anError.localizedDescription
self.hasAlert = true. // ... unable to host Alert().
}
}, receiveValue: { someValue in
print(".sink() received \(someValue)")
})
}
}
问题:为什么我没有通过
收到此alert()(isPresented: $standardWeatherReport.hasAlert)?
答案 0 :(得分:0)
standardWeatherReport.hasAlert
并非来自PublishedWeatherReport
类。
StandardWeatherReport
类在哪里
答案 1 :(得分:0)
我混合了两个出版商。
因此,相关警报无法正常运行。
另外,我还有多个警报运算符,每个发布者一个。
这是一个错误的设计:每个主机只允许一(1)个警报操作员;否则,第二个.alert运算符将覆盖前一个运算符。
因此,如果一个警报处于活动状态,那么随后一个非活动警报操作员将立即取消该警报。