使用 alamofire 上传 pdf 文件

Upload a pdf file with alamofire

我得到了以下从 swagger 代码 gen 创建的函数:

 open class func uploadFile(firstname: String, lastname: String, timestamp: Date, file: URL, completion: @escaping ((_ data: ApiResponse?,_ error: Error?) -> Void)) {

在应用程序中,您可以使用相机拍摄图像并将图像转换为 pdf 文件:

let document = PDFDocument()
let pdfPage = PDFPage(image: unwrapImage)
document.insert(pdfPage!,at: 0)

所以现在我想上传这个文档。但是 document.documentURL 始终为零。虽然我可以在显示器上显示 pdf 文档。我是否应该将 pdf 文档保存到临时目录以使用带有 url 参数的函数?

PDFDocument 的 属性 documentURL 是只获取的。如果你不使用 url 初始化器,它总是 return nil。您需要的是将您的 PDFDocument dataRepresentationwrite pdf 数据保存到临时或永久位置的 url。然后你可以上传它 URL.

let document = PDFDocument()
let image = UIImage(named: "imageName.jpg")!
if let pdfPage = PDFPage(image: image) {
    document.insert(pdfPage,at: 0)
    do {
        print(FileManager.default.temporaryDirectory.path)
        let fileURL = FileManager.default.temporaryDirectory.appendingPathComponent("pdfName.pdf")
        try document.dataRepresentation()?.write(to: fileURL)
        // upload your fileURL or copy to a permanent location
    } catch {
        print(error)
    }
}