2011-08-16 33 views
49

Tôi cố gắng lấy đường dẫn tệp của tệp có tên "temp.pdf" nằm trong thư mục NSTemporaryDirectory (tôi đã kiểm tra, tệp tồn tại).Nhận đường dẫn tệp và URL cho tệp trong thư mục tạm thời

tôi sử dụng này:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"temp" ofType:@"pdf" inDirectory:NSTemporaryDirectory()]; 

Tôi đã thử với:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"temp.pdf" ofType:@"" inDirectory:NSTemporaryDirectory()]; 

Và:

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"temp" ofType:@"pdf"]; 

Nhưng có vẻ như nó không hoạt động, giá trị trả về là luôn luôn rỗng.

Vì vậy, tôi hơi bối rối, ai đó có thể giúp tôi?

Cảm ơn bạn.

Trả lời

120

NSTemporaryDirectory() cung cấp đường dẫn đầy đủ đến thư mục tạm thời. Thay vì sử dụng của bạn mainBundle Bạn đã thử

NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"temp.pdf"]; 

Nếu bạn cần một URL thay vào đó, làm điều này:

NSURL *furl = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:@"temp.pdf"]]; 
+0

OK, khi tôi làm điều đó, tôi muốn sử dụng filepath với [tương tác UIDocumentInteractionControllerControllerWithURL: filepath]; Tôi đã tạo [url url của NSURLWithString: filepath], nhưng Xcode nói: "Lược đồ không hợp lệ (null). Chỉ hỗ trợ lược đồ tệp." – HasgardLucian

+19

Thử 'NSURL * furl = [NSURL fileURLWithPath: [NSTemporaryDirectory() stringByAppendingPathComponent: @" temp.pdf "]];' – Joe

+0

Điều gì xảy ra nếu chúng ta muốn trả về tất cả các tệp pdf trong thư mục tạm thời? –

13

Swift 2,0

let tmpDirURL = NSURL.fileURLWithPath(NSTemporaryDirectory(),isDirectory: true) 
let fileURL = tmpDirURL.URLByAppendingPathComponent("stuff").URLByAppendingPathExtension("gif") 
print("FilePath: \(fileURL.path)") 
0

Đối Swift 3.0

var fileUrl: URL = URL(fileURLWithPath: NSTemporaryDirectory()) 
fileUrl.appendPathComponent("foo") 
fileUrl.appendPathExtension("bar") 
Các vấn đề liên quan