2013-11-23 101 views
5

我很難篩選搜索結果以瞭解如何執行此操作,而且我無法在文檔中找到具體的任何內容。我只想下載一個文件並存儲在Documents目錄中。該文件的類型爲.plist,但我不需要解析plist。就像我說的,我只需要將它保存到磁盤。如何使用AFNetworking 2.0下載文件

我是否使用AFHTTPRequestOperationManager?

這是我一直想一般:

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 
    //manager.responseSerializer = [AFPropertyListResponseSerializer serializer]; 
    manager.responseSerializer = [AFHTTPResponseSerializer serializer]; 

    [manager GET:url parameters:nil 
     success:^(AFHTTPRequestOperation *operation, id responseObject) { 
      DLog(@"downloaded plist"); 
     } 
     failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
      DLog(@"JSON DataError: %@", error); 
     }]; 

如果我使用AFHTTPResponseSerializer我得到這個:

Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: internal server error (500)" 

如果我使用AFPropertyListResponseSerializer我得到這個:

Error Domain=AFNetworkingErrorDomain Code=-1016 "Request failed: unacceptable content-type: text/plain" 

但我甚至不確定我是否使用了正確的API。

+1

(本)[http://stackoverflow.com/questions/8372661/how-to-download-a-file-and-save-it-to-the-文件目錄與聯網]可能有所幫助。 – n00bProgrammer

+0

雖然使用舊版AFNetworking。這仍然是推薦的方式嗎? – soleil

+0

嘗試過,我仍然得到錯誤:錯誤域= AFNetworkingErrorDomain代碼= -1011「請求失敗:內部服務器錯誤(500) – soleil

回答

15

請試試這個例子。 希望得到這個幫助!

// Step 1: create NSURL with full path to downloading file 
// for example try this: NSString *fileUrl = @"https://pbs.twimg.com/profile_images/2331579964/jrqzn4q29vwy4mors75s_400x400.png"; 
// And create NSURLRequest object with our URL 
NSURL *URL = [NSURL URLWithString:fileUrl]; 
NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 

// Step 2: save downloading file's name 
// For example our fileName string is equal to 'jrqzn4q29vwy4mors75s_400x400.png' 
NSString *fileName = [URL lastPathComponent]; 

// Step 3: create AFHTTPRequestOperation object with our request 
AFHTTPRequestOperation *downloadRequest = [[AFHTTPRequestOperation alloc] initWithRequest:request]; 

// Step 4: set handling for answer from server and errors with request 
[downloadRequest setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { 
      // here we must create NSData object with received data... 
      NSData *data = [[NSData alloc] initWithData:responseObject]; 
      // ... and save this object as file 
      // Here 'pathToFile' must be path to directory 'Documents' on your device + filename, of course 
      [data writeToFile:pathToFile atomically:YES]; 
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) { 
      NSLog(@"file downloading error : %@", [error localizedDescription]); 
     }]; 

// Step 5: begin asynchronous download 
[downloadRequest start]; 

別的東西:What's the best way to find the user's Documents directory on an iPhone?

+1

寫一些解釋tooo。 –

+1

對不起,我的不好回答:) Now這個更好嗎? –

+1

可以請你告訴我,如果同樣的請求會執行多次?如果已經有相同的請求運行,我們可以在開始下載之前檢查嗎? –