I ended up using @Sergey Kuryanov's second approach since the first one did not work for me. I was using UIWebView's loadHTMLString
method so you will see that in the code but you can replace it with whatever method you are using to load data in the UIWebView.
The first thing to do was to subscribe to rotation notifications. To do that I followed @clearwater82's answer on the matter in this question: How to detect rotation for a programatically generated UIView
I rewrote his answer for Swift 3, you can find it in the same page.
Once that was done it was easy to reload the data in the UIWebView using loadHTMLString
. My approach was to wrap the UIWebView inside a custom view so I could also handle some formatting of the HTML directly inside my custom view. This made it very simple to add the "reload-on-rotation" feature. Here is the code I used, more details in the linked answer:
// Handle rotation
UIDevice.current.beginGeneratingDeviceOrientationNotifications()
NotificationCenter.default.addObserver(
self,
selector: #selector(self.orientationChanged(notification:)),
name: NSNotification.Name.UIDeviceOrientationDidChange,
object: nil
)
// Called when device orientation changes
func orientationChanged(notification: Notification) {
// handle rotation here
self.webView.loadHTMLString(self.htmlText, baseURL: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
UIDevice.current.endGeneratingDeviceOrientationNotifications()
}
I just want to point out two things:
self.htmlText
is a variable holding the HTML text I want to load that I added to my custom view
- the use of
UIDevice.current.endGeneratingDeviceOrientationNotifications()
was appropriate for my situation, it might not be for yours
That's all, cheers