Fatal error: Unexpectedly found nil while unwrapping an Optional value
I am stuck on why I keep getting the error above
var linkFileSize = ""
class ViewController: NSViewController, URLSessionDelegate, URLSessionDownloadDelegate {
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
let filesize = Int64(linkFileSize)!
let percentage = CGFloat(totalBytesWritten) / CGFloat(filesize)
DispatchQueue.main.async{
print("\(Int(percentage * 100))%")
}
}
@IBAction func buttonClicked(_ sender: Any) {
DownloadFile(downloadFile: downloadString)
}
func DownloadFile(downloadFile:String){
let configuration = URLSessionConfiguration.default
let urlSession = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
guard let url = URL(string: downloadFile) else {return}
let downloadTask = urlSession.downloadTask(with: url)
downloadTask.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
downloadString = "My Download String from AWS"
let fileSizeString = "set DLSize to do shell script(\"curl -s '\(downloadString)' | wc -c\") as text"
linkFileSize = runAppleScriptString(aString: fileSizeString)
}
func runAppleScriptString(aString: String) -> String{
var error: NSDictionary?
if let scriptObject = NSAppleScript(source: aString) {
let output: NSAppleEventDescriptor = scriptObject.executeAndReturnError(&error)
print(output.stringValue ?? "")
if (error != nil) {
print("errorString: \(String(describing: error))")
return ("errorString: \(String(describing: error))")
}
return output.stringValue ?? "\(String(describing: error))"
}
return ""
}
}
I am trying to get the percentage of my download. I am able to get the size of the file as well as downlaod the file with no issues but when I try to get the percentage I run into an issue. When I print out the value of linkFileSize I get the correct size of the file. But then when I try to cast it to Int64 to the fileSize variable I keep getting a crash that the value is nil. How can the value be nil when I am able to print it out and see the value before right when the view loads but when I click the button and begin the DownloadFile function the value is suddenly nil?