Shalina Hu
Shalina Hu

Reputation: 31

Safari view controller

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.

Upvotes: 3

Views: 4897

Answers (2)

David S.
David S.

Reputation: 6705

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.

Upvotes: 8

necatievrenyasar
necatievrenyasar

Reputation: 136

this work for me but wkwebview. https://github.com/liqichao/wkwebview-test

this example is a sfsafariview but u must use inner with wkwebview https://github.com/mattneub/Programming-iOS-Book-Examples/blob/master/bk2ch11p552webkit/ch24p825webview/WebViewController.swift

Upvotes: 0

Related Questions