我正在使用Firebase的iOS数据库,并且设置了常规的数据检索功能,可以在其中将数据打印到控制台,但是我想将数据发布为PDF。问题在于,PDF在Closure之前渲染,因此Firebase中的数据不会发布。我还需要有多个Closure,因为我从数据库中的几个不同位置获取数据。目前,我正在尝试将Firebase的其中一部分仅转换为PDF图纸
override func viewDidLoad() {
super.viewDidLoad()
var recipEmail = ""
let userID = Auth.auth().currentUser!.uid
var refLegal = DatabaseReference()
var refBank = DatabaseReference()
var refOther = DatabaseReference()
let font = UIFont(name: "Helvetica Bold", size: 8.0)
let fileName = "pdffilename.pdf"
var pathForPDF = ""
var heightSoFar = 25
let textColor = UIColor.black
var paragraphStyle:NSMutableParagraphStyle = NSMutableParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
var textFontAttributes = [NSAttributedString.Key : NSObject]()
let textRect = CGRect(x: 5, y: 3, width: 125, height: 18)
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0] as! NSString
pathForPDF = documentsDirectory.appending("/" + fileName)
UIGraphicsBeginPDFContextToFile(pathForPDF, CGRect(), nil)
UIGraphicsBeginPDFPageWithInfo(CGRect(x: 0, y: 0, width: 100, height: 400), nil)
paragraphStyle.alignment = NSTextAlignment.left
paragraphStyle.lineBreakMode = NSLineBreakMode.byWordWrapping
textFontAttributes = [
NSAttributedString.Key.font: font!,
NSAttributedString.Key.foregroundColor: textColor,
NSAttributedString.Key.paragraphStyle: paragraphStyle
]
Database.database().reference().child("\(userID)/legalInf").observeSingleEvent(of : .value, with : {(Snap) in
if let snapDict = Snap.value as? [String:AnyObject]{
var i = 0
for each in snapDict{
var legalO = LegalInfoStorage();
legalO.name = each.value["name"] as! String
legalO.id = each.value["id"] as! String
legalO.phone = each.value["phone"] as! String
legalO.firm = each.value["firm"] as! String
legalO.address = each.value["address"] as! String
legalO.email = each.value["email"] as! String
legalO.address = each.value["address"] as! String
let y = 75*i + 25
let tR = CGRect(x:5, y:y, width: 200, height: 75)
let te = legalO.toString() as NSString
//print(te)
i += 1
te.draw(in: tR, withAttributes: self.textFontAttributes)
print("closure")
}
}
})
let text:NSString = "Name's Instructions"
text.draw(in: textRect, withAttributes: textFontAttributes)
print("drew")
UIGraphicsEndPDFContext()
//I have an outlet for the view not shown in this code
let pView = PDFView(frame: viewForPDF.bounds)
pView.autoScales = true
viewForPDF.addSubview(pView)
// Create a PDFDocument object and set it as PDFView's document to load the document in that view.
let pdfDocument = PDFDocument(url: URL(fileURLWithPath: pathForPDF))!
pView.document = pdfDocument
}
我有打印语句,以便可以看到首先运行哪个代码,这就是我得到的输出:
画了
关闭
关闭
因此,这意味着PDF在运行检索代码之前已在绘制,因此它仅显示“名称的说明”