Сценарий: Я хочу иметь возможность отображать Alert () из наблюдаемого объекта через значения @Published (networkMessage & hasAlert).
Это предупреждение должно срабатывать при отсутствии сетевого подключения. через
Просмотр хоста , который отображает предупреждение ():
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")
}
}
}
Наблюдаемый объект изначально срабатывает Alert () через case .failure (let anError):
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)")
})
}
}
Вопрос: Почему я не получаю это предупреждение () через
(isPresented: $standardWeatherReport.hasAlert)?