I’m working on an iOS app with Swift and I’m stuck. I’m trying to get files from Google Drive using WKWebView, but nothing happens when I tap the download button. Here’s what I’ve done so far:
import UIKit
import WebKit
class MainViewController: UIViewController, WKNavigationDelegate, WKDownloadDelegate {
var browserView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
let config = WKWebViewConfiguration()
browserView = WKWebView(frame: view.bounds, configuration: config)
browserView.navigationDelegate = self
browserView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(browserView)
NSLayoutConstraint.activate([
browserView.topAnchor.constraint(equalTo: view.topAnchor),
browserView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
browserView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
browserView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
if let gdURL = URL(string: "GOOGLE_DRIVE_FILE_LINK") {
let req = URLRequest(url: gdURL)
browserView.load(req)
}
}
func webView(_ webView: WKWebView, navigationResponse: WKNavigationResponse, didBecome download: WKDownload) {
download.delegate = self
print("Download started")
}
func download(_ download: WKDownload, decideDestinationUsing response: URLResponse, suggestedFilename: String, completionHandler: @escaping (URL?) -> Void) {
let docsPath = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let saveURL = docsPath.appendingPathComponent(suggestedFilename)
completionHandler(saveURL)
print("File will be saved at: \(saveURL)")
}
func downloadDidFinish(_ download: WKDownload) {
print("Download finished")
}
func download(_ download: WKDownload, didFailWithError error: Error, resumeData: Data?) {
print("Download error: \(error.localizedDescription)")
}
}
Is this approach even possible? Should I try URLSession instead? Or maybe use the Google Drive API? Also, can I still download files using direct URLs? Any help would be great!