這個問題有兩個部分。首先,將基礎字符串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)
凡視圖控制器符合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!
}
}
來源
2017-07-04 05:05:35
Rob
如果讓數據=數據(base64Encoded:base64String){ VAR字符串=字符串(數據:data,encoding:.utf8) } –
在這段代碼中字符串變量打印爲零 –
這個也是在Base64到NSData之間完成的St環。 –