如何从Swift中的JSON下载PDF文件和iOS中的Alamofire



如何使用Swift 3.0和Alamofire在iOS中下载PDF文件。我能够用nsurlsession获取URL。但是我正在寻找Alamofire代码。请参阅我的代码。

func downloadPdffile(_ sender : UIButton) {
    print(sender.tag)
    print("ARRAY VALUES FROM CELL",totalSyllabusArray.object(at: sender.tag))
    var localDic :NSDictionary!
    localDic = totalSyllabusArray.object(at: sender.tag) as! NSDictionary
    let filepath = localDic["filepath"] as! String
    print("pressed ")
    let strURL1:String = FETCH_InMegh_Image_BaseURL + filepath
    print("strURL1 is ",strURL1)
    let pathURL = URL(string: strURL1)!
    let sessionConfig = URLSessionConfiguration.default
    let session = URLSession(configuration: sessionConfig)
    let request = try! URLRequest(url: pathURL, method: .get)
    let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
        if let tempLocalUrl = tempLocalUrl, error == nil {
            // Success
            if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                print("Success: (statusCode)")
                print("tempLocalUrl: (tempLocalUrl)")
                              } else {
                print("Failure: %@", error?.localizedDescription);
            }
        }
    }
}

}

定义您的destination类似的内容:

let destination: DownloadRequest.DownloadFileDestination = { _, _ in
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let fileURL = documentsURL.appendingPathComponent("your.pdf")
    return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}  

并用您的URL和目的地致电Alamofire.download

Alamofire.download(yourUrl), to: destination).response { response in
        let parentView = (self.superview?.superview as! UITableView).dataSource as! ProcedureViewController
        parentView.hideActivityIndicator()
        if response.error == nil, let _ = response.destinationURL?.path {
            //open pdf in UIDocumentInteractionController
            self.docController = UIDocumentInteractionController.init(url: response.destinationURL!)
            self.docController?.delegate = self.delegate!
            self.docController?.name = ""
            self.docController?.presentOptionsMenu(from: self.parentView!.bounds, in: self.parentView!, animated: true)
        }
    }

最新更新