
Of course, it would be great if your iOS app users would always have a 100% working WiFi or Cellular connection. But reality is different and we should know how to handle it 😉 So let’s make the best out of it and present a nice Offline screen for these annoying situations of being offline:
Step 1: Design a sad smiley or something similar 😉
Step 2: Open your main storyboard in Xcode/Interface Builder and insert the image using UIImageView; call it offlineImageView.
Step 3: Create a UILabel saying something like “Please check your internet connection” and call it lblText1.
Step 4: The user should be able to retry without reloading the whole app (which would require killing it from the multitasking switcher). That’s why we add a “Try again” UIButton now – let’s call it btnTry.
Step 5: Make sure to hide all created elements of step 2 to 4 at the beginning of your app launch and after every successful loading of WebView pages:
webView.isHidden = false offlineImageView.isHidden = true lblText1.isHidden = true btnTry.isHidden = true
Step 6: When your WebView loads any URL, check the mobile connection of the user and catch connection errors:
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error)
{
if((error as NSError).code == NSURLErrorNotConnectedToInternet)
{
if(!isFirstTimeLoad)
{
let alertController = UIAlertController(title: offlinetitle, message: offlinemsg, preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: okbutton, style: UIAlertActionStyle.cancel, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
}
isFirstTimeLoad = false
webView.isHidden = true
offlineImageView.isHidden = false
lblText1.isHidden = false
btnTry.isHidden = false
}
}
If you use the WebViewGold Xcode template (or WeSetupYourWebViewApp service), you do not need to worry about the whole Offline screen creating process. It just looks great:
Any questions? Just email us! 🙂