Swift 3.0 FileManager.fileExists(atPath:) always return false

前端 未结 7 2167
一向
一向 2021-02-05 00:38

When I use method .fileExists(atPath:)to judge whether the file is exist in file system, the method always return false to me. I checked the file system and the fil

7条回答
  •  猫巷女王i
    2021-02-05 00:51

    I assume your url is an URL type. If so try this out:

    let filePath = url?.path  // always try to work with URL when accessing Files
    if(FileManager.default.fileExists(atPath: filePath!)){  // just use String when you have to check for existence of your file
        let result = NSData(contentsOf: url!)  // use URL instead of String
    }
    

    Saying enough, you should change your implementation like this:

    if(FileManager.default.fileExists(atPath: (url?.path)!)){  // just use String when you have to check for existence of your file
        let result = NSData(contentsOf: url!)  // use URL instead of String
    }
    

    EDIT: 1

    There is even more better way, you can call it swift-way (:D). You don't have to explicitly check for file existence.

    guard let result = NSData(contentsOf: fileURL) else {
        // No data in your fileURL. So no data is received. Do your task if you got no data
        // Keep in mind that you don't have access to your result here.
        // You can return from here. 
        return
    }
    // You got your data successfully that was in your fileURL location. Do your task with your result.
    // You can have access to your result variable here. You can do further with result constant.
    print(result)
    

    Update for Swift 3.0+ without the Objective-Cish NS prefix:

    do {
        let result = try Data(contentsOf: fileURL)
        print(result)
    } catch {
        print(error)
    }
    

提交回复
热议问题