I have a class, MyURL, from a UIKit app that I wrote that handles all my URL needs, uploads, downloads, GETS, POSTS, etc.
I would like to use that class from within a SwiftUI view now. So the SwiftUI view that creates calls MyURL methods. And I would pass binding vars that would cause my SwiftUI view to update things such as statuses : percentage done, etc.
My issue is, how can I properly declare that class, myURL, from within the SwiftUI view, so that it doesn't get redeclared every time the view updates.
Should I declare the MyURL class in a view above it and pass it into the view that calls the MyUrl class? Would just like to do it the proper way.
I wish I was better with terminology.
Thank you
struct ContentView: View {
**var myURL = MyURL()**
@State var proceed = false
var body: some View {
Button {
myURL.pressed(proceed: $proceed)
}
label: {
Text(proceed ? "pressed" : "not pressed")
}
}
}
class MyURL: NSObject, URLSessionDataDelegate,URLSessionTaskDelegate, URLSessionDelegate, URLSessionDownloadDelegate{
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
}
func pressed(proceed: Binding<Bool>) {
print("\(proceed)")
proceed.wrappedValue.toggle()
}
// Error received
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if let err = error {
DispatchQueue.main.async { [self] in
//code
}
}
}
// Response received
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: (URLSession.ResponseDisposition) -> Void) {
completionHandler(URLSession.ResponseDisposition.allow)
if let httpResponse = response as? HTTPURLResponse {
xFile?.httpResponse = httpResponse.statusCode
DispatchQueue.main.async { [self] in
if httpResponse.statusCode != 200 {
//code
}
}
}
}
// Data received
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
if xFile?.httpResponse == 200 {
DispatchQueue.main.async { [self] in
//code
}
} //DispatchQueue.main.async
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let num : Float = Float(totalBytesWritten * 100)
let den : Float = Float(totalBytesExpectedToWrite * 100)
let percentDownloaded : Int = Int(num/den * 100)
DispatchQueue.main.async { [self] in
//code
}
}
}