Mischa Mischa - 2 months ago 169
iOS Question

How to display a PDF without a base URL in a UIWebView in Swift 3?

I want to display a PDF file in a

UIWebView
. I already have it as a
Data
object so I don't need to (and cannot) provide a
baseURL
.

In Objective-C ...



... the corresponding method was defined as follows:

- (void)loadData:(NSData *)data
MIMEType:(NSString *)MIMEType
textEncodingName:(NSString *)textEncodingName
baseURL:(NSURL *)baseURL;


so I could simply pass
nil
as
baseURL
as documented in Apple's Text Programming Guide.

In Swift 2.0 ...



... the
baseURL
parameter is not optional in the
load(...)
function (why?) so I had to pass a valid
NSURL
object. Fortunately, there was an easy workaround described in another Stackoverflow post: I simply created an empty
NSURL
object.

private func showPdf(data: NSData) {
webView.loadData(data,
MIMEType: "application/pdf",
textEncodingName: "utf-8",
baseURL: NSURL())
}


Now in Swift 3.0 ...



... the method signature has changed and the
baseURL
parameter has to be a Swift
URL
instead of
NSURL
:

open func load(_ data: Data,
mimeType MIMEType: String,
textEncodingName: String,
baseURL: URL)


This breaks the workaround because for
URL
there is no empty initializer and creating a
URL
from an empty string is not possible as stated in the Swift documentation:

/// Returns `nil` if a `URL` cannot be formed with the string
/// (for example, if the string contains characters that are illegal
/// in a URL, or is an empty string).
public init?(string: String)


So the question is:

How can I load a PDF (or any other web content) without providing a
baseURL
inside a
UIWebView
in Swift 3?

Answer

Usually if you have data it came through a URL to start with, so just use that URL.

Or I suppose you could use the file URL of anything inside your app bundle as the base URL.

Or maybe you can form the URL as an NSURL and cast to URL with as.

Or save the data to disk and call loadRequest instead.

Comments