首次编译时在Swift崩溃时编程

时间:2019-11-26 20:55:08

标签: swift

因此,我使用swift运行了此代码,而我遇到的问题是,在第一次编译项目时,它不起作用。但是,当我停止该项目并再次运行它时,它可以很好地工作,并且我重复了几次,因此不再出现此问题。更具体地说,当项目打开并且我按应用程序上的按钮时,转到我在下面显示的错误:

这是我第一次运行该错误

  

“线程1:致命错误:“尝试!”表情意外地引起了   错误:错误域= NSCocoaErrorDomain代码= 260“文件“ .tmp”   无法打开,因为没有这样的文件。”   UserInfo = {NSFilePath = /。tmp,NSUnderlyingError = 0x60000335d9b0 {Error   Domain = NSPOSIXErrorDomain代码= 2“没有这样的文件或目录”}}“

此错误显示在创建let contentstring的行上。我检查contentstring的值,然后得到那个contentstring =(NSString)0x0000000000000000。多次运行该程序时,它为我提供了一个有效值,并且运行良好。

我不确定为什么在按下按钮时只会发生一次此错误,这是解决该问题的可靠方法。

import UIKit

class KresgePorter: UIViewController, UITableViewDataSource, UITableViewDelegate {

   var printString: String!

   var array: [String] = []

   var count: Int = 0

  override func viewWillAppear(_ animated: Bool) {
       super.viewWillAppear(animated)
       navigationController?.setNavigationBarHidden(true, animated: false)

   }

   override func viewDidLoad() {
       super.viewDidLoad()

       /*-------------------------------------------------------------------------------------------------------------------------------------------------*/
               var nameTXT = ""
               var documentsDir = ""

               let website = some string url

               guard let url1 = URL(string: website) else { return  }

               //This portion of the code focuses on creating a download task with a completion handler
               //Completion handler moves the downloaded file to the app's directory

               let downloadTask = URLSession.shared.downloadTask(with: url1) {
                   urlOrNil, responseOrNil, errorOrNil in
                   // check for and handle errors:
                   // * errorOrNil should be nil
                   // * responseOrNil should be an HTTPURLResponse with statusCode in 200..<299
                   print("Went into the let\n")
                   guard let fileURL = urlOrNil else { return }
                   do {
                       let documentsURL = try
                           FileManager.default.url(for: .documentDirectory,
                                                   in: .userDomainMask,
                                                   appropriateFor: nil,
                                                   create: true)
                       let savedURL = documentsURL.appendingPathComponent(fileURL.lastPathComponent)
                       let filename = fileURL.lastPathComponent
                       let fileName2 = URL(fileURLWithPath: filename).deletingPathExtension().lastPathComponent
                       nameTXT = fileName2
                       print("the content of nameTXT is: \(nameTXT)")

                       try FileManager.default.moveItem(at: fileURL, to: savedURL)
                   } catch {
                       print ("file error: \(error)")
                   }
                   let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
                   documentsDir = paths.firstObject as! String
                   print("Path to the Documents directory\n\(documentsDir)")

               }
               downloadTask.resume()


               //If you want to receive progress updates as the download proceeds, you must use a delegate.
               var urlSession = URLSession(configuration: .default, delegate: self as? URLSessionDelegate, delegateQueue: nil)

               func startDownload(url1: URL){
                   print("Went into the startDownload function\n")
                   let downloadTask = urlSession.downloadTask(with: url1)
                   //let fname = downloadTask.response?.suggestedFilename
                   downloadTask.resume()
               }

               startDownload(url1: url1)

       /*-----------------------------------------------------------------------------------------------------*/
               usleep(270000)

               let directPath = documentsDir + "/" + nameTXT + ".tmp"
               let url = URL(fileURLWithPath: directPath)
               let contentString = try! NSString(contentsOf: url, encoding: String.Encoding.utf8.rawValue)

               printString = contentString as String

               let fullName = printString
               array = fullName!.components(separatedBy: "\n")


       // Do any additional setup after loading the view.
   }

   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

       return array.count

   }

   func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

       let cell = tableView.dequeueReusableCell(withIdentifier: "breakfast", for: indexPath)
       cell.textLabel?.text = array[indexPath.row]
       return cell

   }

}

1 个答案:

答案 0 :(得分:1)

我不应该在生产代码中使用try!

let contentString = try! NSString(contentsOf: url, encoding: String.Encoding.utf8.rawValue)

转换为此:

do {
    let contentString = try? String( url, encoding: .utf8)
} catch {
    print(error)
}

实际的问题是:

let directPath = documentsDir + "/" + nameTXT + ".tmp"
let url = URL(fileURLWithPath: directPath)

产生"/.tmp"。这是无效的网址。

这是因为documentsDirnameTXT都为空。

所以,核心原因是您打电话

let directPath = documentsDir + "/" + nameTXT + ".tmp"
let url = URL(fileURLWithPath: directPath)

在服务器响应回调之外。

只需将代码从

中移出
// If you want to receive progress updates as the download until 
array = fullName!.components(separatedBy: "\n")

此行后立即关闭:

print("Path to the Documents directory\n\(documentsDir)")

您的关闭操作是异步启动的。