2017-05-05 104 views
0

我正在使用Alamofire從服務器下載文件。但我想它命名爲不同就像我們從網站上下載文件,並可以將其命名爲我們想要的,同樣的,這怎麼可能在迅速使用Swift保存具有不同名稱的文件

我使用下面的代碼: -

Alamofire.download(fileUrl, to: destination) 
     .downloadProgress { progress in 
      print("Download Progress:---------- \ 
     (progress.fractionCompleted)") 


     } 
     .responseData { response in 

      print(response.request) 
      print(response.response) 
      print(response.temporaryURL) 
      print(response.destinationURL) 
      print(response.error) 

    } 

建議不要使用alamofire重命名或覆蓋文件。是否有任何其他方法

+0

您是否想將自定義名稱的下載數據保存到應用的文檔目錄? –

+0

是的,我想在文檔目錄中保存具有不同名稱的文件 – mirza

+0

請查看我的答案。如果您遇到任何問題,請告訴我。 –

回答

0

這裏是手動功能將您的Data保存到DocumentDirectory與您給出的名稱。該方法有一個call back,執行保存操作後會調用它,它將返回保存在目錄中的圖像的路徑。這個函數寫在Swift 3

func saveImageInDocDirectory(data: Data?, fileName: String?, successblock: @escaping (_ path: String?) -> Void) { // To add the image to cache for given identifier. 

    let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as String 
    let path = paths.appending("/\(fileName!)") 
    if !FileManager.default.fileExists(atPath: path) { 
     do { 
      try FileManager.default.createDirectory(at: URL(fileURLWithPath: path), withIntermediateDirectories: false, attributes: nil) 
     } catch { 
      print("Error creating images folder in Cache dir: \(error)") 
     } 
    } 

    if (filemgr.fileExists(atPath: path)) { 
     try! filemgr.removeItem(atPath: path) 
    } else { 
     do { 
      try data?.write(to: URL(fileURLWithPath: path, isDirectory: false)) 
      successblock(path) 
     } catch { 
      successblock(nil) 
      print("Error while caching the data in cache folder.") 
     } 
    } 

} 

,你可以調用此方法一樣,

Alamofire.download(fileUrl, to: destination) 
    .downloadProgress { progress in 
     print("Download Progress:---------- \ 
    (progress.fractionCompleted)") 


    } 
    .responseData { response in 

     print(response.request) 
     print(response.response) 
     print(response.temporaryURL) 
     print(response.destinationURL) 
     print(response.error) 
     if let data = response.result.value { 
     self.saveImageInDocDirectory(data: data, fileName: "YourFile", successblock: { (path) in 

       print(path) 

      } 
     } 

} 

感謝。

+0

感謝您的幫助!但我正在使用Alamofire按照要求下載內容。 – mirza

+0

我也使用alamofire下載數據。請看我更新的答案。 –

+0

你有沒有試過我的答案? –

相關問題