1. 程式人生 > >關於AFUrlSessionManager下載檔案報The file couldn’t be opened because the specified URL type isn’t support問題

關於AFUrlSessionManager下載檔案報The file couldn’t be opened because the specified URL type isn’t support問題

今天遇到一個問題,就是用AFUrlSessionManager下載檔案的時候,下載過程中一切正常,但是去解壓這個檔案的時候,卻發現該檔案不存在,找了半天還以為是路徑有問題,確定了很多遍發現路徑沒有問題,最後一點點跟程式碼才發現問題原因,這裡記錄一下。

AFUrlSessionManager下載檔案的流程是先將檔案下載到一個臨時資料夾下面,然後移動到指定的目錄下面並重新命名,問題就是發生在這裡,打斷點發現是移動.tmp檔案的時候出錯了,移動檔案的程式碼如下:

if (self.downloadTaskDidFinishDownloading) {
        self.downloadFileURL
= self.downloadTaskDidFinishDownloading(session, downloadTask, location); if (self.downloadFileURL) { [[NSFileManager defaultManager] moveItemAtURL:location toURL:self.downloadFileURL error:&fileManagerError]; NSLog(@"fileManagerError=%@",fileManagerError); if
(fileManagerError) { [[NSNotificationCenter defaultCenter] postNotificationName:AFURLSessionDownloadTaskDidFailToMoveFileNotification object:downloadTask userInfo:fileManagerError.userInfo]; } } }

錯誤資訊如下:

The file couldn’t be opened because the specified URL
type isn’t supported.

最後發現,這個NSFileManager讀取本地檔案的時候,必須加上file://這個url頭,不然就會報這個錯,我這裡的兩個引數location和self.downloadFileURL前者有加這個頭,後者是自己定義的沙盒路徑沒有加這個,所以移動檔案的時候會報錯,使用[NSURL fileURLWithPath:filePath]返回的就是加上了file://頭的本地路徑了。

另外需要注意的是,如果目標路徑下存在了名稱一樣的檔案,是移不過去的,需要先將同名檔案刪除,再移動。