2017-05-05 55 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

你有没有试过我的答案? –

相关问题