2017-05-05 10 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) 

    } 

- :しかし、私はそれが可能であるSWIFT

に、私は次のコードを使用していますどのように同じ、ちょうど私たちはウェブからファイルをダウンロードし、私たちが望むように名前を付けることができますどのように異なった名前を付けたいですファイル名の変更や上書きにalamofireを使用しないことを推奨します。他の方法

+0

ダウンロードしたデータをカスタム名でアプリのドキュメントディレクトリに保存しますか? –

+0

はい、ドキュメントディレクトリに異なる名前のファイルを保存します – mirza

+0

私の答えを見てください。あなたがこの問題に直面した場合は私に教えてください。 –

答えて

0

がここにあり、関数の手があなたが与えられた名前を使用してDataにDocumentDirectoryを保存することです。このメソッドには、保存アクションを実行した後に呼び出されるcall backという1つがあり、ディレクトリに保存されたイメージのパスが返されます。この関数は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

あなたは私の答えを試しましたか? –

関連する問題