提问人:joefooodie 提问时间:11/14/2023 最后编辑:Joakim Danielsonjoefooodie 更新时间:11/14/2023 访问量:50
从从 ViewController 生成的 URL 创建 WebView 时遇到问题
Having Trouble Creating a WebView from a URL Generated from a ViewController
问:
“accountURL”在 ViewController 中成功生成了一个链接(在调用 OURFILE.PHP)。我需要在不同的视图中引用此 accountURL 以创建 Web 浏览器弹出窗口。
但是,当我尝试在 viewController 中将此变量定义为“tacos”并尝试引用“tacos”并在单击“Connect with Stripe”后弹出 WebView 时,应该出现的弹出浏览器不会显示 URL 并显示“无效 URL”(我的调试语句的一部分)。
下面是视图控制器:
import UIKit
import SafariServices
let BackendAPIBaseURL: String = “OURFILE.PHP” // Set to the URL of your backend server
class ConnectOnboardViewController: UIViewController {
// ...
var tacos: String = ""
override func viewDidLoad() {
super.viewDidLoad()
let connectWithStripeButton = UIButton(type: .system)
connectWithStripeButton.setTitle("Connect with Stripe", for: .normal)
connectWithStripeButton.addTarget(self, action: #selector(didSelectConnectWithStripe), for: .touchUpInside)
view.addSubview(connectWithStripeButton)
// ...
}
@objc
func didSelectConnectWithStripe() {
if let url = URL(string: BackendAPIBaseURL)?.appendingPathComponent("onboard-user") {
var request = URLRequest(url: url)
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
guard let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String : Any],
let accountURLString = json["url"] as? String,
let accountURL = URL(string: accountURLString)
else {
// handle error
return
}
print(accountURL)
self.tacos = accountURL.absoluteString
}
task.resume()
}
}
}
extension ConnectOnboardViewController: SFSafariViewControllerDelegate {
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
// the user may have closed the SFSafariViewController instance before a redirect
// occurred. Sync with your backend to confirm the correct state
}
}
以下是带有“Connect with Stripe”按钮的视图:
Button {
self.isLoading = true
ConnectOnboardViewController().didSelectConnectWithStripe()
self.link = Link(link: ConnectOnboardViewController().tacos)
print(ConnectOnboardViewController().tacos)
self.isLoading = false
} label: {
HStack {
Image("Vector-4").resizable().scaledToFit().frame(height: 17)
Rectangle().fill(Color.white)
.frame(width: 1.3, alignment: .center)
.padding(.vertical,10)
.padding(.horizontal, 10)
Text("Connect with Stripe").foregroundColor(.white)
.font(.system(size: 16, weight: .regular))
}
.padding(.horizontal, 40)
.frame(height: 50)
.background(Color.appColor)
.cornerRadius(15)
}.frame(height: 100)
Spacer()
}
}
}
.background(Color.white)
.cornerRadius(20, corners: [.topLeft,.topRight])
.sheet(item: self.$link) { link in
if let url = URL(string: link.link) {
WebView(url: url)
} else {
Text("Invalid URL")
}
}
我尝试在视图控制器中定义变量并将 url 传递给视图。
我希望看到一个带有 safari 弹出窗口的 WebView,其中包含在 ViewController 的“tacos”中定义的 url。
希望您有什么建议,如何在不同的视图中引用从视图控制器生成的链接?
答: 暂无答案
评论
other