How can I read a file in a swift playground

后端 未结 9 1845
时光说笑
时光说笑 2020-12-12 22:37

Im trying to read a text file using a Swift playground with the following

let dirs : String[]? =    NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory         


        
9条回答
  •  粉色の甜心
    2020-12-12 22:44

    String.stringWithContentsOfFile is DEPRECATED and doesn't work anymore with Xcode 6.1.1

    Create your documentDirectoryUrl

    let documentDirectoryUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first! as NSURL
    

    To make sure the file is located there you can use the finder command Go To Folder e copy paste the printed documentDirectoryUrl.path there

    println(documentDirectoryUrl.path!)
    // should look like this: /Users/userName/Library/Containers/com.apple.dt.playground.stub.OSX.PLAYGROUNDFILENAME-5AF5B25D-D0D1-4B51-A297-00015EE97F13/Data/Documents
    

    Just append the file name to the folder url as a path component

    let fileNameUrl = documentDirectoryUrl.URLByAppendingPathComponent("ReadMe.txt")
    var fileOpenError:NSError?
    

    Check if the file exists before attempting to open it

    if NSFileManager.defaultManager().fileExistsAtPath(fileNameUrl.path!) {
    
        if let fileContent = String(contentsOfURL: fileNameUrl, encoding: NSUTF8StringEncoding, error: &fileOpenError) {
            println(fileContent)        // prints ReadMe.txt contents if successful
        } else {
            if let fileOpenError = fileOpenError {
                println(fileOpenError)  // Error Domain=NSCocoaErrorDomain Code=XXX "The file “ReadMe.txt” couldn’t be opened because...."
            }
        }
    } else {
        println("file not found")
    }
    

提交回复
热议问题