请求 URL 并在警报中解析结果
Posted
技术标签:
【中文标题】请求 URL 并在警报中解析结果【英文标题】:Requesting URL and Parsing The Result In A Alert 【发布时间】:2020-06-26 21:48:25 【问题描述】:我已将变量设为全局变量,但我无法弄清楚在收到响应后如何显示警报。不确定我是否必须创建功能。任何事情都会有所帮助。
代码:https://hastebin.com/izurihadib.swift
struct ContentView: View
@State private var showingAlert = false
var body: some View
TabView
var str1 = ""
var fullStr = ""
Button(action:
self.showingAlert = true
AF.request("https://api-quiz.hype.space/shows/now").responseJSON response in
switch response.result
case .success(let value):
let json = JSON(value)
debugPrint(json)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let dt = dateFormatter.date(from: json["nextShowTime"].stringValue)
dateFormatter.timeZone = TimeZone.current
dateFormatter.dateFormat = "MMM d, yyyy h:mm a"
let nextGameName = json["upcoming"][0]["nextShowLabel"]["title"].stringValue
let tempStr1 = "Next Game: "
str1 = tempStr1 + nextGameName
let nextGamePrize = json["nextShowPrize"].stringValue
let tempStr2 = "Prize: "
let str2 = tempStr2 + nextGamePrize
let nextGameTime = dateFormatter.string(from: dt!)
let tempStr3 = "Date/Time: "
let str3 = tempStr3 + nextGameTime
fullStr = str2 + "\n" + str3
case .failure(let error):
print(error)
)
Text("Get Info")
.alert(isPresented: $showingAlert)
Alert(title: Text(str1), message: Text(fullStr), dismissButton: .default(Text("OK")))
.tabItem
Image(systemName: "phone.fill")
Text("First Tab")
Text("The content of the second view")
.tabItem
Image(systemName: "tv.fill")
Text("Second Tab")
【问题讨论】:
请不要在其他网站上发布您的代码,尽量方便那些可能选择帮助您的人。请阅读the Stack Overflow question checklist。您可能还想了解Minimal, Complete, and Verifiable Examples 尝试将self.showingAlert = true
放入网络请求的成功案例中。t
它仍然显示空白警报。
【参考方案1】:
您需要进行以下更改才能解决您的问题。
struct ContentView: View
@State private var showingAlert = false
@State private var str1 = ""
@State private var fullStr = ""
var body: some View
TabView
Button(action:
self.showingAlert = true
AF.request("https://api-quiz.hype.space/shows/now").responseJSON response in
switch response.result
case .success(let value):
//...
case .failure(let error):
self.str1 = "Error"
self.fullStr = "\(error)"
self.showingAlert = true
)
Text("Get Info")
.alert(isPresented: $showingAlert)
Alert(title: Text(str1), message: Text(fullStr), dismissButton: .default(Text("OK")))
//...
【讨论】:
以上是关于请求 URL 并在警报中解析结果的主要内容,如果未能解决你的问题,请参考以下文章