2009-10-03 39 views
73

我有一個NSURL對象,它給了我一個本地文件(在文檔文件夾中)的路徑。我想用這個文件的內容填充一個NSData對象。嘗試使用dataWithContentsOfURL:但這失敗。我知道該文件存在,因爲iPhone SDK返回路徑。iPhone - 從本地文件的URL的NSData

有人可以告訴我如何從本地文件的URL獲得NSData對象嗎?

謝謝。

+0

「但它失敗」是什麼意思? – Marco 2009-10-03 17:37:21

+0

意味着它在此凍結!給出一個例外。我試圖訪問一個視頻的數據,我們從UIImagePickerController得到的URL。 – lostInTransit 2009-10-03 17:41:43

+0

似乎你想傳遞一個不是NURL的對象。你如何獲得文件的URL,你確定是一個URL而不是NSString? – Marco 2009-10-03 17:47:55

回答

146
// Given some file path URL: NSURL *pathURL 
// Note: [pathURL isFileURL] must return YES 
NSString *path = [pathURL path]; 
NSData *data = [[NSFileManager defaultManager] contentsAtPath:path];
+1

contentsOfFile將帶有文件路徑的NSString。我得到一個NSURL對象。 – lostInTransit 2009-10-03 17:44:36

+0

我不確定,但是,使用defaultManager而不是alloc,init可能會導致線程問題。 – carlossless 2013-03-20 15:35:23

+2

[NSFileManager文檔](https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSFileManager_Class/Reference/Reference.html)在Threading Considerations下面有這樣的說法:「The共享的NSFileManager對象的方法可以安全地從多個線程調用。「他們注意到的唯一例外是,如果您打算處理來自文件管理器操作的委託回調;我不相信這適用於此。 – Tim 2013-03-20 21:42:01

24

爲了得到這個工作,你只需要做:

NSURL *imgPath = [[NSBundle mainBundle] URLForResource:@"search" withExtension:@"png"]; 
NSString*stringPath = [imgPath absoluteString]; //this is correct 

//you can again use it in NSURL eg if you have async loading images and your mechanism 
//uses only url like mine (but sometimes i need local files to load) 
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringPath]]; 
UIImage *ready = [[[UIImage alloc] initWithData:data] autorelease]; 
1

確保您的本地URL開頭「文件://」 那麼你就只需要做到這一點:

NSData *fileData = [NSData dataWithContentsOfFile:fileURL.path]; 
+0

下找到它。url總是以assets-library://asset/asset.MOV?id = 095AA9E9-A4F5-4035- 9A21-3CFF04F45C70&ext = MOV @ahbou – 2017-08-17 10:15:49

+0

這僅適用於資產(照片和視頻)。 OP從文檔文件夾 – ahbou 2017-08-17 10:36:40

+0

請求一個文件,當我從asset_library中選定的URL創建數據對象時,它給我無@ahbou – 2017-08-17 10:47:31

0

對於swift3我找到答案從以下網址有用

(我得到下面的路徑,使用PhoneGap的插件

文件來捕獲圖像之後:///var/mobile/Containers/Data/Application/B64B06DE-7976-45CF-9BE2-661F0F309A06/tmp/abcded.jpg)

https://stackoverflow.com/a/41043447/6383908

如果讓videoURL = URL(字符串:urlString),讓可視數據=試試?數據(contentsOf:videoURL){ //在此處添加Alamofire的代碼 }