Testing file existence using NSURL

前端 未结 6 2075
失恋的感觉
失恋的感觉 2020-12-07 20:10

Snow Leopard introduced many new methods to use NSURL objects to refer to files, not pathnames or Core Services\' FSRefs.

However, there\'s one task I can\'t find a

6条回答
  •  甜味超标
    2020-12-07 20:21

    In Swift you can use the checkResourceIsReachable() method, which unfortunately will either return true (if the file is reachable) or throw an error (explaining why it cannot be reached).

    To get a bool true/false value instead, use this syntax:

    let exists = (try? inputFile.checkResourceIsReachable()) ?? false
    

    If you'd like to log the error:

    let exists: Bool
    do {
      exists = try inputFile.checkResourceIsReachable()
    } catch {
      exists = false
      print(error.localizedDescription)
    }
    

    Keep in mind this is an expensive operation and it could be out of date immediately after (if some other process is deleting a or unmounts a disk file while you're checking if it exists).

    In general the preferred approach is not to check wether a file exists, instead simply attempt to read or write to a file and handle any error afterwards if it fails.

提交回复
热议问题