gpt4 book ai didi

swift 3 : PDFDocument crashes

转载 作者:行者123 更新时间:2023-11-28 12:27:21 26 4
gpt4 key购买 nike

我正在尝试编写一个简单的函数来获取 PDF 中的页数。我现在看到的每个代码示例似乎都无法使用 Swift 3,而且 Xcode 推荐的任何内容仍然不起作用。

func pageCount(filepath: String) -> Int {

let localUrl = filepath as CFString
let pdfDocumentRef = CFURLCreateWithFileSystemPath(nil, localUrl, CFURLPathStyle.cfurlposixPathStyle, false)
let page_count = (pdfDocumentRef as! CGPDFDocument).numberOfPages

return page_count
}

这也行不通:

func pageCount(filepath: String) -> Int {

let url = NSURL(fileURLWithPath: filepath)
let pdf = CGPDFDocument(url)
let page_count = pdf?.numberOfPages

return page_count!
}

有什么想法吗?

最佳答案

修改你的代码如下:

func pageCount(filepath: String) -> Int {
var count = 0
let localUrl = filepath as CFString
if let pdfURL = CFURLCreateWithFileSystemPath(nil, localUrl, CFURLPathStyle.cfurlposixPathStyle, false) {
if let pdf = CGPDFDocument(pdfURL) {
let page_count = pdf.numberOfPages
count = pdf.numberOfPages
}
}
return count
}

基本上,在您的代码中,您试图将 CFURL 转换为 CGPDFDocument 而您不能这样做:) 您需要创建一个 CGPDFDocument 来自 CFURL 的实例。执行此操作后,您可以获得 PDF 文档的页数。

关于 swift 3 : PDFDocument crashes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43016399/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com