1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
| import CallKit
class ViewController: UIViewController, WKScriptMessageHandler, WKUIDelegate, WKNavigationDelegate, MFMessageComposeViewControllerDelegate, CXCallObserverDelegate {
let callObserver = CXCallObserver() private var beforeDate: Date!
public func callPhone(phoneStr: String) { let phone = "telprompt://" + phoneStr if let url = NSURL(string: phone.replacingOccurrences(of: " ", with: "", options: .literal, range: nil)), UIApplication.shared.canOpenURL(url as URL) { callObserver.setDelegate(self, queue: DispatchQueue.main) didDetectOutgoingCall = false UIApplication.shared.open(url as URL, options: [:]) { [weak self] success in if success { DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { self?.addNotifObserver() } } } } }
func addNotifObserver() { let selector = #selector(appDidBecomeActive) let notifName = UIApplication.didBecomeActiveNotification NotificationCenter.default.addObserver(self, selector: selector, name: notifName, object: nil) }
@objc func appDidBecomeActive() { DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) { [weak self] in if !(self?.didDetectOutgoingCall ?? true) { print("Cancel button pressed") } } }
func callObserver(_: CXCallObserver, callChanged call: CXCall) {
if call.isOutgoing, call.hasConnected, !call.hasEnded { setBeginDate() } if call.isOutgoing, call.hasConnected, call.hasEnded { let seconds = getCallPhoneTime()
webView.evaluateJavaScript("callPhone(\(seconds))") { _, error in print("Error : \(String(describing: error))") } } }
func setBeginDate() { beforeDate = Date() }
func getCallPhoneTime() -> String { let dat = Date(timeInterval: 0, since: beforeDate) let a = dat.timeIntervalSinceNow
let timeString = String(format: "%0.f", fabs(a)) print("\(timeString)秒") return timeString } }
|