ios - 如何在 ios 中从 swift 和 alamofire 中的 json 下载 pdf 文件?

标签 ios json swift pdf 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);
            }
        }
    }
}

最佳答案

像这样定义你的目的地:

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)
        }
    }

关于ios - 如何在 ios 中从 swift 和 alamofire 中的 json 下载 pdf 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46210798/

相关文章:

ios - 使用 Swift 在键盘上启动一个带有搜索按钮的新 View Controller

ios - RxSwift 将 Observable<Bool> 转换为 Observable<Void>

ios - UITextField 字符限制

python - 如何将 JSON 字符串转换为 Python 中的字典?

javascript - 在 javascript 中解析类似 json 的结构/字符串

ios - 如何获取 SWIFT 3 中特定控件的标识符名称(通过 Storyboard创建)以从数据库设置值

swift - 字典中可选值的意外 nil 检查结果

ios - View 仅在应用程序重启后由 EnvironmentObject 更新

ios - 如何在 IOS 中开始单用户聊天?

ios - 已解析的 JSON 字符串未在 VC 之间共享