2015-11-08 21 views
9

tôi cần phải lấy URL của một tài nguyên chứa trong dự án Xcode của mình thông qua một con đường mà bắt đầu trong thư mục của dự án (aka mainBundle)Nhận URL nguồn từ đường dẫn cụ thể dự án

Vì vậy, nếu đường dẫn cụ thể của tôi nếu ./snd /archer/acknowledge1.wav, tôi cần tạo URL từ đó.

Tôi biết tôi có thể sử dụng NSURL(fileURLWithPath:) cho các thư mục hệ thống, nhưng tôi không biết cách thực hiện việc này trực tiếp từ gói.

Trả lời

11

Bạn sẽ sử dụng một trong những phương pháp URL bó resourse

[[NSBundle mainBundle] URLForResource:@"acknowledge1" 
         withExtension:@"wav" 
         subdirectory:@"snd/archer"]; 

NSBundle.mainBundle().URLForResource("acknowledge1", withExtension:"wav" subdirectory:"snd/archer") 

Trong mới nhất Swift:

Bundle.main.url(forResource: "acknowledge1", withExtension:"wav") 
23

Tính Swift 3, câu trả lời là:

Bundle.main.url(forResource: "acknowledge1", withExtension: "wav" subdirectory: "snd/archer") 
+0

Hãy sửa câu trả lời của bạn. Cần dấu phẩy trước 'thư mục con'. Đây là câu trả lời tuyệt vời cho Swift 4 (và có thể là Swift 3) –

0

Trong Swift 2.3 y ou'd phải sử dụng này unwrapping:

if let resourceUrl = NSBundle.mainBundle().URLForResource("acknowledge1", withExtension: "wav", subdirectory:"snd/archer") { 
     if NSFileManager.defaultManager().fileExistsAtPath(resourceUrl.path!) { 
      print("file found") 
      //do stuff 
     } 
    } 
Các vấn đề liên quan