Xcode keeps saying
Invalid redeclaration of ‘ContentView’
Instance will be immediately deallocated because property ‘navigationDelegate’ is ‘weak’ * ‘weak’ may only be applied to class and class-bound protocol types, not ‘FilesView’ * Value of type ‘WebViewCoordinator’ has no member ‘getDocumentsDirectory’ * Value of type ‘WebViewCoordinator’ has no member ‘sanitizeFileName’
Value of type ‘[URLResourceKey: Any]’ has no member ‘totalFileAllocatedSize’
heres the code: l
`
import SwiftUI
import WebKit
@main
struct UDOWNLOADERZApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
var body: some View {
TabView {
BrowserView()
.tabItem {
Label("Browser", systemImage: "globe")
}
FilesView()
.tabItem {
Label("Files", systemImage: "folder")
}
SettingsView()
.tabItem {
Label("Settings", systemImage: "gearshape")
}
}
}
}
struct BrowserView: View {
@State private var webView = WKWebView()
var body: some View {
WebView(webView: $webView)
.onAppear {
let urls = ["https://youtube.com", "https://soundcloud.com"]
for url in urls {
if let url = URL(string: url) {
let request = URLRequest(url: url)
webView.load(request)
}
}
webView.navigationDelegate = WebViewCoordinator(filesView: nil)
}
}
}
struct WebView: UIViewRepresentable {
@Binding var webView: WKWebView
func makeUIView(context: Context) -> WKWebView {
return webView
}
func updateUIView(_ uiView: WKWebView, context: Context) {}
}
class WebViewCoordinator: NSObject, WKNavigationDelegate {
weak var filesView: FilesView?
init(filesView: FilesView?) {
self.filesView = filesView
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
let jsCode = """
(function() {
var video = document.querySelector('video');
var audio = document.querySelector('audio');
var mediaElement = video || audio;
if (mediaElement) {
return {
src: mediaElement.src,
title: document.title || mediaElement.getAttribute('title') || 'Unknown'
};
}
return null;
})();
"""
webView.evaluateJavaScript(jsCode) { [weak self] (result, error) in
guard let resultDict = result as? [String: String], let urlString = resultDict["src"], let title = resultDict["title"], let url = URL(string: urlString) else { return }
self?.downloadContent(url: url, title: title)
}
}
func downloadContent(url: URL, title: String) {
DispatchQueue.global().async {
let destinationURL = getDocumentsDirectory().appendingPathComponent("(sanitizeFileName(fileName: title)).mp4")
URLSession.shared.downloadTask(with: url) { [weak self] (tempURL, response, error) in
guard let self = self, let tempURL = tempURL, error == nil else { return }
do {
try FileManager.default.moveItem(at: tempURL, to: destinationURL)
DispatchQueue.main.async {
NotificationCenter.default.post(name: NSNotification.Name("DownloadCompleted"), object: nil)
self.filesView?.reloadFilesList()
}
} catch {
print("Download failed: (error.localizedDescription)")
}
}.resume()
}
}
}
struct FilesView: View {
@State private var downloadedFiles = [String]()
@State private var storageTaken: String = ""
var body: some View {
VStack {
List {
ForEach(downloadedFiles, id: .self) { file in
Text(file)
}
}
Text("Storage Taken: (storageTaken)")
}
.onAppear(perform: loadFiles)
.onReceive(NotificationCenter.default.publisher(for: NSNotification.Name("DownloadCompleted"))) { _ in
loadFiles()
}
}
func loadFiles() {
DispatchQueue.global().async {
do {
let files = try FileManager.default.contentsOfDirectory(at: getDocumentsDirectory(), includingPropertiesForKeys: nil, options: [])
DispatchQueue.main.async {
downloadedFiles = files.map { $0.lastPathComponent }
calculateStorageTaken(files: files)
}
} catch {
print("Failed to load files: (error.localizedDescription)")
}
}
}
func reloadFilesList() {
loadFiles()
}
private func calculateStorageTaken(files: [URL]) {
let size = files.reduce(0, { $0 + ($1 as NSURL).fileSize() })
storageTaken = ByteCountFormatter.string(fromByteCount: Int64(size), countStyle: .file)
}
}
struct SettingsView: View {
var body: some View {
VStack {
Text("Contact: [email protected]")
Text("Twitter: N/A")
}
}
}
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
func sanitizeFileName(fileName: String) -> String {
let invalidCharacters = CharacterSet(charactersIn: "\/:*?"<>|")
return fileName.components(separatedBy: invalidCharacters).joined(separator: "_")
}
extension NSURL {
func fileSize() -> Int {
guard`
`
I tried rejusting the code and it still didnt work.
rights4a is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.