rac*_*rma 4 base64 nsdata ios pdf-viewer swift
我是 IOS 的新手,我正在制作一个项目,在该项目中我从 Web 服务接收 Base64 数据。如何将 Base64 数据转换为字符串以及如何在 swift 中打开 pdf 视图,并检查 iPhone 中是否安装了任何 pdf 所有者应用程序。我想知道如何在字符串 swift 中转换 NSDATA。帮我举例,例如这是Base64数据JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nLVcza8ct5GH1rK9ejIU24lkO5GtJ8vWm5E87eY3uXtbYLHAYi8 JdItySrABAjhA8v8fUuwmu35kF2fmxbsWDMxjk8VisapYX+TfbudJ6ds5/6s//vj
就像这样 nsdata <25504446 2d312e34 0a25c7ec 8fa20a35 2030206f 626a0a3c 3c2f4c65 6e677468 20362030 20522f46 696c7465 72202f46 6c617465 44 65636f 64653e3e 0a737472 65616d0a 789cb55c cdaf1cb7 9187d6b2 bd7a3214 db89643b 91ad27cb d69b913c
这个问题有两个部分。首先,将 Base 64 字符串转换为Data/ NSData。但你已经做到了,所以你不需要帮助。
其次,将Data/转换NSData为字符串。但是,如果您仔细查看该文件,您会发现数据是 PDF 文件,而不是文本字符串。例如,如果我将其另存为文件并在十六进制编辑器中查看它,我可以清楚地看到它是 PDF:
您不能只将 PDF 二进制数据转换为字符串。(事实上,这就是为什么它首先进行 Base64 编码,因为它是复杂的二进制数据。)
但是,例如,您可以用来UIDocumentInteractionController预览保存到文件的 PDF 文件。
例如:
// convert base 64 string to data
let base64 = "JVBERi0xLjQKJcfsj6IKNSAwIG9iago8PC9MZW5ndGggNiAwIFIvRmlsdGVyIC9GbGF0ZURlY29kZT4+CnN0cmVhbQp4nLVcza8ct5GH1rK9ejIU24lkO5GtJ8vWm5E87eY3uXtbYLHAYi8JdItySrABAjhA8v8fUuwmu35kF2fmxbsWDMxjk8VisapYX+TfbudJ6ds5/6s/"
guard let data = Data(base64Encoded: base64) else {
print("unable to convert base 64 string to data")
return
}
// given the data was PDF, let's save it as such
let fileURL = try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false)
.appendingPathComponent("test.pdf")
try! data.write(to: fileURL)
// if it was a string, you could convert the data to string, but this will fail
// because the data is a PDF, not a text string
//
// guard let string = String(data: data, encoding: .utf8) else {
// print("Unable to convert data into string")
// return
// }
// print(string)
// So, instead, let's use `UIDocumentInteractionController` to preview the PDF:
let controller = UIDocumentInteractionController(url: fileURL)
controller.delegate = self
controller.presentPreview(animated: true)
Run Code Online (Sandbox Code Playgroud)
其中,视图控制器符合UIDocumentInteractionControllerDelegate:
extension ViewController: UIDocumentInteractionControllerDelegate {
func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
return self
// or, if this view controller is already in navigation controller, don't
// return `self`, like above, but instead return the navigation controller itself
//
// return navigationController!
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7781 次 |
| 最近记录: |