简体   繁体   English

启动 SwiftUI 计时器

[英]Starting the SwiftUI Timer

Please tell me, is there such a code.请告诉我,有没有这样的代码。 When you click on webview, a timer starts and after 5 seconds a notification is displayed.当您单击 webview 时,计时器启动,5 秒后显示通知。 How to make the timer start immediately without clicking on webview (delete button action).如何在不单击 webview 的情况下立即启动计时器(删除按钮操作)。 By default, webview should start.默认情况下,webview 应该启动。

import SwiftUI
import WebKit
import UserNotifications

struct ContentView: View {
  @State var alert = false
  var body: some View {
    Button(action: {
      UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) {
        (status, _) in
        if status {
          let content = UNMutableNotificationContent()
          content.title = "HEAD"
          content.body = "TEXT"
          let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
          let request = UNNotificationRequest(identifier: "noti", content: content, trigger: trigger)
          UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
          return
        }
        self.alert.toggle()
      }

    }) {
      WebView().edgesIgnoringSafeArea(.all)
    }.alert(isPresented: $alert) {
      return Alert(title: Text("Please Enable Notification Access In Settings Pannel !!!"))
    }
  }
}

struct WebView: UIViewRepresentable {
  func makeUIView(context: Context) - > WKWebView {
    let webView = WKWebView()
    webView.scrollView.isScrollEnabled = false
    return webView
  }


  func updateUIView(_ webView: WKWebView, context: Context) {
    let liveView = "https:/*"
    if let url = URL(string: liveView) {
      let request = URLRequest(url: url)
      webView.load(request)
      let timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) {
        (timer) in
        webView.evaluateJavaScript("document.getElementById('ses').value") {
          (result, error) in
          print(result!)
        }
      }
    }
  }
}

struct ContentView_Previews: PreviewProvider {
  static
  var previews: some View {
    ContentView()
  }
}

you can start timer immediately by using fire() method您可以使用fire()方法立即启动计时器

like this :像这样 :

let timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) {
        (timer) in
        webView.evaluateJavaScript("document.getElementById('ses').value") {
          (result, error) in
          print(result)
        }
}
timer.fire()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM