简体   繁体   中英

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. How to make the timer start immediately without clicking on webview (delete button action). By default, webview should start.

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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