2016-09-04 6 views
0

このAlamofireの方法で外部pdfファイルをダウンロードします。ダウンロードしたファイル(キャッシュ)を次回アプリケーションに開く

問題は、次回ユーザーがアプリケーションを開いたときに問題が残っていることです。したがって、ユーザーはpdfを再度ダウンロードする必要はありません。

私はdownloadedFilePathは、このようなものである

let destination = 
     Alamofire.Request.suggestedDownloadDestination(directory: .CachesDirectory, 
                 domain: .UserDomainMask); 

    Alamofire.download(.GET, urlString, destination: destination) 
     .progress { bytesRead, totalBytesRead, totalBytesExpectedToRead in 

     } 
     .response { request, response, _, error in 

      print("Downloaded to \(destination(NSURL(string: "")!, response!))"); 

    } 

をダウンロードするには、次のメソッドを使用します。

file:///var/mobile/Containers/Data/Application/4957AD15-947A-47D6-A126-EA06A5BCB099/Library/Caches/RewardMe-Presentation-at-NVIDIA-Auditorium.pdf 

次回のアプリケーション起動時にファイルを保存するにはどうすればよいですか?

次回のアプリケーション起動時にそのパスをNSUserDefaultsに保存しましたが、ファイルは既に消えています。

+0

NSDocumentDirectoryまたはNSBundleにファイルを保存してから、そこから入手してください –

+0

どうすれば実現できますか? @AbdulRehmanWarraich – JayVDiyk

答えて

0

コードに2つの機能を追加して、copyFileを呼び出して、パスを表示します。

func getPath(fileName: String) -> String { 

     let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] 
     let fileURL = documentsURL.URLByAppendingPathComponent(fileName) 


     print("File Path Is : \(fileURL)") 

     return fileURL.path! 
    } 

func copyFile(fileName: NSString , filePath : NSString) { 
     let dPath: String = getPath(fileName as String) 
     let fileManager = NSFileManager.defaultManager() 
     if !fileManager.fileExistsAtPath(dPath) { 



      let fromPath : NSURL = NSURL.fileURLWithPath(filePath);    
      var error : NSError? 
      do { 
       try fileManager.copyItemAtPath(fromPath.path!, toPath: dPath) 
      } catch let error1 as NSError { 
       error = error1 
      } 
      let alert: UIAlertView = UIAlertView() 
      if (error != nil) { 
       alert.title = "Error Occured" 
       alert.message = error?.localizedDescription 
      } else { 
       alert.title = "Successfully Copy" 
       alert.message = "Your File copy successfully" 
      } 
      alert.delegate = nil 
      alert.addButtonWithTitle("Ok") 
      alert.show() 
     } 
    } 

コピーファイル 2パラメータ1が保存したいと、ファイルが置かどこ秒があるファイルのファイル名です。

また、次回にアプリケーションを開くときに何をするかを確認するためです。最初にファイルのパスを取得し、ファイルが存在するかどうかを確認します。存在しない場合は、ファイルをダウンロードしないでください。

let filePath: String = getPath("testFile.pdf") 
     let fileManager = NSFileManager.defaultManager() 
     if fileManager.fileExistsAtPath(dPath) { 
     //Code for using the file data 
     } 
else { 
//Download code for the file 
} 

はそれが役に立てば幸い:)

0

HTTPはすでにキャッシュメカニズムを持っている、あなたはそれを使用することを検討してください可能性があります。車輪を再発明しないでください。 Hereはそれを行う方法です。

関連する問題