I am new in iOS app development. Currently, I am working on a project which requires the interaction between the app and webpage. I know I can use safari view controller to load a web page within the app, and use done button at the right up corner of the webpage to back to the app. But I want to back to the app by clicking a link in the webpage instead of done button. I could not find any solution for this. Can anyone help? Many thanks in advance.
You can do this easily enough with a custom URL scheme. First add a scheme to your Info.plist:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.mydomain.MyCallback</string>
<key>CFBundleURLSchemes</key>
<array>
<string>mydomainwebcallback</string>
</array>
</dict>
</array>
Now, you have a mechanism that will open your app from any URL that is clicked. In this case, the url would be mydomainwebcallback://whatever
Now in your web page loaded in your view controller, add a URL like this:
<a href="mydomainwebcallback://whateverinfo">Return to app</a>
I am going to simplify here, but you need a reference to your SFSafariViewController from your AppDelegate. First in the AppDelegate:
import UIKit
import SafariServices
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var safariVC: SFSafariViewController?
func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
// Here we dismiss the SFSafariViewController
if let sf = safariVC
{
sf.dismissViewControllerAnimated(true, completion: nil)
}
return true
}
As you can see I am keeping the SFSafariViewController in the Delegate. Now in my view controller where I show the VC:
import UIKit
import SafariServices
class ViewController: UIViewController {
@IBAction func showSafariVC(sender: UIButton) {
if let url = NSURL(string: "https://mywebserver/callback.html")
{
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
delegate.safariVC = SFSafariViewController(URL: url)
presentViewController(delegate.safariVC!, animated: true, completion: nil)
}
}
}
Now, when you hit the link it will dismiss the SFSafariViewController.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With