title: warning: attempt to present whose view is not in the window hierarchy
body: <p>I have a UITabView in UIViewController, all tab items are linked to other UIViewControllers. I have written a swift code of downloading a file through internet. when I select second tabItem, this code runs well, it downloads and previews the downloaded file, Then when I click on first tabItem and then again click on second tabItem; file downloads well but it doesn't show any preview instead xCode gives me a warning message: 
  What I want is download file and preview file both should work when I again click on the second tabItem. whatever the code is.</p>
  
  <blockquote>
    <p>warning: attempt to present QLPreviewController on KPIViewController  whose view is not in the window hierarchy</p>
  </blockquote>
  
  <p>I have found many solutions on the internet but it didn't work</p>
  
  <p>first solution says to use </p>
  
  <pre><code> let viewer = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: path))
   UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(viewer, animated: true, completion: nil)
  </code></pre>
  
  <p>but this function</p>
  
  <pre><code>UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(viewer, animated: true, completion: nil)
  </code></pre>
  
  <p>do not accept 
   <code>UIDocumentInteractionController</code></p>
  
  <p>second solution says to override the existing <code>presentViewController</code> function to </p>
  
  <pre><code>override func presentViewController(viewControllerToPresent: UIViewController, animated flag: Bool, completion: (() -&gt; Void)?) {
  
          let APP_DELEGATE = UIApplication.sharedApplication().delegate
          var presentedModalVC:UIViewController = (APP_DELEGATE!.window?!.rootViewController?.presentedViewController)!
  
          if presentedModalVC == true {
  
              while((presentedModalVC.presentedViewController) != nil){
  
                  presentedModalVC = presentedModalVC.presentedViewController!
              }
              presentedModalVC.presentViewController(viewControllerToPresent, animated: flag, completion: nil)
          }
          else{
              APP_DELEGATE?.window!!.rootViewController?.presentViewController(viewControllerToPresent, animated: flag, completion: nil)
          }
      }
  </code></pre>
  
  <p>I tried this but it also needs a UIViewController in its parameters where I have <code>UIDocumentInteractionController</code>
  I know these function cannot accept <code>UIDocumentInteractionController</code> type viewController. </p>
  
  <p>here is my whole swift code: </p>
  
  <pre><code>//  KPIViewController.swift
  //  download
  //
  //  Created by me on 15/03/2016.
  //  Copyright © 2016 me. All rights reserved.
  //
  
  import UIKit
  
  class KPIViewController: UIViewController,UITabBarDelegate, NSURLSessionDownloadDelegate, UIDocumentInteractionControllerDelegate{
  
      @IBOutlet weak var tabBar1: UITabBar!
      @IBOutlet weak var login_Item: UITabBarItem!
      @IBOutlet weak var QAreport_Item: UITabBarItem!
  
  
      @IBOutlet weak var KpiWebView: UIWebView!
      @IBOutlet weak var progressView: UIProgressView!
  
      var downloadTask: NSURLSessionDownloadTask!
      var backgroundSession: NSURLSession!
  
      var downloadReport:Bool!
  
      var AuditCodeOfDashboardCell:String?
      var AuditCodeForPDF:String?
      let isDirectory: ObjCBool = false
  
  
      override func viewDidLoad() {
          super.viewDidLoad()
  
          self.progressView.hidden = true
          downloadReport = false
  
          // Do any additional setup after loading the view.
          self.tabBar1.delegate = self
  
      }
  
      override func viewDidAppear(animated: Bool) {
  
          self.progressView.hidden = true
  
          downloadReport = false
  
          let backgroundSessionConfiguration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier("backgroundSession")
          backgroundSession = NSURLSession(configuration: backgroundSessionConfiguration, delegate: self, delegateQueue: NSOperationQueue.mainQueue())
          progressView.setProgress(0.0, animated: false)
  
  
          var requestURL = NSURL!()
          var request = NSURLRequest!()
          // loading data from web
  
          if AuditCodeOfDashboardCell != nil{
              print(self.AuditCodeOfDashboardCell)
              requestURL = NSURL(string:“my URL string&amp;\(AuditCodeOfDashboardCell)”)
              request = NSURLRequest(URL: requestURL!)
              AuditCodeForPDF = AuditCodeOfDashboardCell
              AuditCodeOfDashboardCell = nil
  
          }else{
              requestURL = NSURL(string:“my URL string”)
              request = NSURLRequest(URL: requestURL!)
          }
          KpiWebView.loadRequest(request)
      }
  
      override func didReceiveMemoryWarning() {
          super.didReceiveMemoryWarning()
          // Dispose of any resources that can be recreated.
      }
  
      func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
  
          print("selected tabItem: \(item.tag)")
          switch (item.tag) {
          case 1:
              let loginVC = self.storyboard!.instantiateViewControllerWithIdentifier("loginViewController") as! LoginView
              presentViewController(loginVC, animated: true, completion: nil)
  
              break
          case 2:
              if AuditCodeForPDF != nil{
  
                  downloadReport = true
  
                  let url = NSURL(string: “my URL string&amp;\(AuditCodeForPDF)”)!
                  urlToDownload = url
              }
  
  //                if let resultController = storyboard!.instantiateViewControllerWithIdentifier(“2”) as? QAReportViewController {
  
  //                    presentViewController(resultController, animated: true, completion: nil)
  //                }
  
              break
  
          default:
              break
          }
  
          if downloadReport == true{
  
              let url = NSURL(string: “my URL string&amp;\(AuditCodeForPDF)”)!
  
              downloadTask = backgroundSession.downloadTaskWithURL(url)
              self.progressView.hidden = false
              downloadTask.resume()
              downloadReport = false
  
          }
      }
  
      // - - Handling download file-  - - - - - -  - -
  
      func URLSession(session: NSURLSession,
          downloadTask: NSURLSessionDownloadTask,
          didFinishDownloadingToURL location: NSURL){
  
              let path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
              let documentDirectoryPath:String = path.first!
              let fileManager = NSFileManager()
              var destinationURLForFile = NSURL(fileURLWithPath: documentDirectoryPath.stringByAppendingString("/Report.pdf"))
  
              if fileManager.fileExistsAtPath(destinationURLForFile.path!){
                  //                showFileWithPath(destinationURLForFile.path!)
                  do{
                      try fileManager.removeItemAtPath(destinationURLForFile.path!)
                      destinationURLForFile = NSURL(fileURLWithPath: documentDirectoryPath.stringByAppendingString("/Report.pdf"))
                  }catch{
                      print(error)
                  }
              }
  
              do {
                  try fileManager.moveItemAtURL(location, toURL: destinationURLForFile)
                  // show file
                  dispatch_async(dispatch_get_main_queue(), { () -&gt; Void in
  
                      self.showFileWithPath(destinationURLForFile.path!)
                  })
              }catch{
                  print("An error occurred while moving file to destination url")
              }
  
      }
  
      func showFileWithPath(path: String){
          let isFileFound:Bool? = NSFileManager.defaultManager().fileExistsAtPath(path)
          if isFileFound == true{
              dispatch_async(dispatch_get_main_queue(), { () -&gt; Void in
  
                  let viewer = UIDocumentInteractionController(URL: NSURL(fileURLWithPath: path))
                  viewer.delegate = self
                  viewer.presentPreviewAnimated(true)
              })
  
          }
      }
      func URLSession(session: NSURLSession,
          downloadTask: NSURLSessionDownloadTask,
          didWriteData bytesWritten: Int64,
          totalBytesWritten: Int64,
          totalBytesExpectedToWrite: Int64){
              progressView.setProgress(Float(totalBytesWritten)/Float(totalBytesExpectedToWrite), animated: true)
      }
  
      func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -&gt; UIViewController{
          return self
  
      }
      func documentInteractionControllerDidEndPreview(controller: UIDocumentInteractionController) {
          print("document preview ends")
  
      }
  
  }
  </code></pre>
  
  <p>I cannot find any proper solution that solve my problem. I am new with swift
  please anyone on help me. Thanks in advance</p>