import Foundation
import Intents
import SafariServices
import AVFoundation
func askForInput() -> String {
let intent = INCreateNoteIntent()
intent.title = "Please enter your question"
let interaction = INInteraction(intent: intent, response: nil)
interaction.donate { (error) in
if let error = error {
print("Error donating interaction: \(error)")
}
}
var inputString = ""
let semaphore = DispatchSemaphore(value: 0)
INInteraction.delete(with: [.all]) { (error) in
if let error = error {
print("Error deleting interactions: \(error)")
semaphore.signal()
return
}
INVoiceShortcutCenter.shared.getAllVoiceShortcuts { (voiceShortcuts, error) in
if let error = error {
print("Error getting voice shortcuts: \(error)")
semaphore.signal()
return
}
if let shortcut = voiceShortcuts?.first(where: { $0.invocationPhrase == "Ask for input" }) {
shortcut.shortcut.perform(withCompletionHandler: { (intent, error) in
if let question = (intent as? INCreateNoteIntent)?.content {
inputString = question
// Search the internet for an answer
let urlString = "https://www.google.com/search?q=\(inputString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "")"
if let url = URL(string: urlString) {
let safariViewController = SFSafariViewController(url: url)
UIApplication.shared.windows.first?.rootViewController?.present(safariViewController, animated: true, completion: {
// Extract and speak the first answer from the search results
let script = "var elements = document.getElementsByClassName('Z0LcW'); elements.length > 0 ? elements[0].innerText : '';"
safariViewController.dismiss(animated: true) {
let webView = WKWebView(frame: .zero)
UIApplication.shared.windows.first?.rootViewController?.view.addSubview(webView)
webView.isHidden = true
let utterance = AVSpeechUtterance(string: "")
webView.evaluateJavaScript(script) { (result, error) in
if let answer = result as? String, !answer.isEmpty {
utterance.speechString = answer
} else {
utterance.speechString = "I'm sorry, I couldn't find an answer to your question"
}
AVSpeechSynthesizer().speak(utterance)
webView.removeFromSuperview()
semaphore.signal()
}
}
})
}
}
})
} else {
print("No voice shortcut found")
semaphore.signal()
}
}
}
semaphore.wait()
return ""
}