PDFKit で https が表示できない
Macには以前からあったようですが、iOSではiOS11から PDFKit が追加されました。
PDFKit の細かな話は自分で調べてもらうとして、今回は https://...
のPDFが表示されず、対応策がネット上に英語の情報しか見つからなかったので書いておきます。
前提
Xcode | Swift | iOS |
---|---|---|
9.3 | 4.1 | 11.3 |
コード (結論)
let url = URL(string: "https://www.apple.com/business/docs/iOS_Security_Guide.pdf")! let data = try! Data(contentsOf: url) pdfView.document = PDFDocument(data: data)
注意
- 便宜上 force unwrap してますが良くないので適宜修正して下さい
pdfView
はPDFView
のインスタンス
原因
PDFDocument のイニシャライズ時は通常 PDFDocument.init?(url:)
を使うと思いますが、この時 https://
のurlの場合nilが返されます。
PDFDocument(url: URL(string: "http://...")!) // PDFDocument instance returned PDFDocument(url: URL(string: "https://...")!) // nil returned
さらに PDFView
の document
プロパティが PDFDocument?
というようにnilを許容しているので、なにも表示されない原因に気付きにくいです。
// nothing happens pdfView.document = PDFDocument(url: URL(string: "https://...")!)
詳しい事などは 参考 を参考にしてください。
参考
- ios - PDFKit's PDFDocument init(url: URL) does not work with HTTPS - Stack Overflow
- PDFKit | Apple Developer Documentation
- [iOS 11] PDFKit入門 | Developers.IO
後記
もっと英語できるようになりたい(ってかれこれ6年くらいいってる)