我目前正在尝试从当前视图中获取一个PDF,然后将其设置为变量,然后我可以将其上传到Firebase存储,并取回链接。
我已经用以下代码完成了PDF的生成:
func exportToPDF() {
let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let outputFileURL = documentDirectory.appendingPathComponent("SwiftUI.pdf")
//Normal with
let width: CGFloat = 8.5 * 72.0
//Estimate the height of your view
let height: CGFloat = 1000
let charts = SmartSheet()
let pdfVC = UIHostingController(rootView: charts)
pdfVC.view.frame = CGRect(x: 0, y: 0, width: width, height: height)
//Render the view behind all other views
let rootVC = UIApplication.shared.windows.first?.rootViewController
rootVC?.addChild(pdfVC)
rootVC?.view.insertSubview(pdfVC.view, at: 0)
//Render the PDF
let pdfRenderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 8.5 * 72.0, height: height))
DispatchQueue.main.async {
do {
try pdfRenderer.writePDF(to: outputFileURL, withActions: { (context) in
context.beginPage()
pdfVC.view.layer.render(in: context.cgContext)
})
print("wrote file to: (outputFileURL.path)")
} catch {
print("Could not create PDF file: (error.localizedDescription)")
}
}
pdfVC.removeFromParent()
pdfVC.view.removeFromSuperview()
}
我只需要知道怎么把它上传到Firebase。
仅供参考-我已经能够使用以下代码上传UIImages:
func upload(image: UIImage) {
// Create a storage reference
let storageRef = Storage.storage().reference().child("squawks/(v.FirstName)-sqauwk.jpg")
// Resize the image to 200px with a custom extension
// Convert the image into JPEG and compress the quality to reduce its size
let data = image.jpegData(compressionQuality: 0.2)
// Change the content type to jpg. If you don't, it'll be saved as application/octet-stream type
let metadata = StorageMetadata()
metadata.contentType = "(v.FirstName)-sqauwk/jpg"
// Upload the image
if let data = data {
storageRef.putData(data, metadata: metadata) { (metadata, error) in
if let error = error {
print("Error while uploading file: ", error)
}
if let metadata = metadata {
print("Metadata: ", metadata)
}
}
}
}
func getPhotoURL(completion: @escaping (String) -> Void) {
// Create a reference to the file you want to download
let starsRef = Storage.storage().reference().child("squawks/(v.FirstName)-sqauwk.jpg")
// Fetch the download URL
starsRef.downloadURL { url, error in
if let error = error {
// Handle any errors
print("error getting link: (error)")
} else {
// Get the download URL for 'images/stars.jpg'
completion(url!.absoluteString)
}
}
}
//On click of button:
var strURL = ""
upload(image: inputImage!) //inputImage is a UIImage
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
getPhotoURL() { url in
strURL = url
print("STORAGE URL: (strURL)")
}
谢谢!
1条答案
按热度按时间zxlwwiss1#
将
upload
更改为