2014-09-02 2 views
2

Swift에서 파일을 열려고합니다. 그것을 위해 파일 경로를 만듭니다. 작동하지 않습니다.Swift에서 파일의 경로를 만들 수 없습니다.

maaaacy:~ $ pwd 
/Users/tsypa 
maaaacy:~ $ cat a.txt 
test 
maaaacy:~ $ ./a.swift 
nil! 
maaaacy:~ $ 

스크립트 :

#!/usr/bin/xcrun swift 

import Foundation 

var filePath = NSBundle.mainBundle().pathForResource("a", ofType: "txt", inDirectory: "/Users/tsypa") 
if let file = filePath { 
     println("file path \(file)") 
     // reading content of the file will be here 
} else { 
     println("nil!") 
} 

문제점은 무엇입니까?

+0

문제는 파일이 '번들'에 속하지 않는다는 것입니다. 대신에 [NSFileManager'] (https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html)를 사용하십시오 (또는 NSURL 만 필요하면 NSURL을 사용하십시오). 자원의 경로에 대한 참조). – Alladinian

답변

6

스위프트 REPL의 NSBundle.mainBundle()의 경로가 실제로 가리키는 사용하는 경우 :

/Applications/Xcode6-Beta6.app/Contents/SharedFrameworks/LLDB.framework/Versions/A/Resources 

을 대신 NSFileManager를 사용 할 수 있습니다 :

let manager = NSFileManager.defaultManager() 

if manager.fileExistsAtPath("/Users/tsypa/a.txt") { 
    // file exists, read 
} else { 
    // file doesn't exist 
} 

참고 : 당신은 실제로 수 전체 사용자의 홈 경로를 하드 코딩하지 않도록 경로에서 물결표를 자동으로 확장합니다.