Search code examples
swiftxcode7

Load page into webview swift 2 from java class


I am developing an App for the iPhone using Xwebview which enables me to download a page then interact with the javascript on the downloaded page. All works, but if the internet connection drops, a default local page is loaded, informing the user there is no internet connection. The page displays a retry button that, when pressed checks, the internet connection: if the connection is made the app tries to connect again to the external page and load the page into the webview. I cannot get this to work: the code downloads the page (I can see this in my session data) but I can't get that page to load back into the webview.

override func viewDidLoad() {
        super.viewDidLoad()
              login()
        }

    func login()
    {
        // *********** Get stored hashkey **************
        let hashcode = getHashcode()

        // ********** Check network connection *********
        let netConnection = Connection.isConnectedToNetwork()
        print("net connection: ", netConnection)

        if netConnection == true
        {
            if hashcode != "00000"
            {

                print("local key found", hashcode)
                // We dont have local key
                let webview = WKWebView(frame: view.frame, configuration: WKWebViewConfiguration())
                //webview.loadRequest(NSURLRequest(URL: NSURL(string: "about:blank")!))
                view.addSubview(webview)
                webview.loadPlugin(jsapi(), namespace: "jsapi")


                let url:NSURL = NSURL(string: serverLocation + onlineLoginApi)!
                let session = NSURLSession.sharedSession()
                let request = NSMutableURLRequest(URL: url)

                request.HTTPMethod = "POST"
                request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

                let paramString = "/?username=username&password=password"
                request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

                let task = session.downloadTaskWithRequest(request) {
                    (
                    let location, let response, let error) in

                    guard let _:NSURL = location, let _:NSURLResponse = response  where error == nil else {
                        print("error")
                        return
                    }

                    let urlContents = try! NSString(contentsOfURL: location!, encoding: NSUTF8StringEncoding)

                    guard let _:NSString = urlContents else {
                        print("error")
                        return
                    }

                    print(urlContents)

                }

                task.resume()

                // you must tell webview to load response
                webview.loadRequest(request)

            }
            else{

                print("local key found", hashcode)
                // ********* Found local key go to site pass key over ************

                let webview = WKWebView(frame: view.frame, configuration: WKWebViewConfiguration())
                view.addSubview(webview)
                webview.loadPlugin(jsapi(), namespace: "jsapi")

                let req = NSMutableURLRequest(URL: NSURL(string:serverLocation + onlineLoginApi + "?hashcode=\(hashcode)")!)
                req.HTTPMethod = "POST"
                req.HTTPBody = "/?hashcode=\(hashcode)".dataUsingEncoding(NSUTF8StringEncoding)
                NSURLSession.sharedSession().dataTaskWithRequest(req)
                { data, response, error in
                    if error != nil
                    {
                        //Your HTTP request failed.
                        print(error!.localizedDescription)
                    } else {
                        //Your HTTP request succeeded
                        print(String(data: data!, encoding: NSUTF8StringEncoding))
                    }
                    }.resume()
                webview.loadRequest(req)

            }

        }
        else{

            // No connection to internet

            let webview = WKWebView(frame: view.frame, configuration: WKWebViewConfiguration())
            view.addSubview(webview)
            webview.loadPlugin(jsapi(), namespace: "jsapi")

            let root = NSBundle.mainBundle().resourceURL!
            let url = root.URLByAppendingPathComponent("/www/error-no-connection.html")
            webview.loadFileURL(url, allowingReadAccessToURL: root)
            print("No internet connection")

            }
    }
class jsapi: NSObject {


        // Reconnect button on interface
        func retryConnection()
        {
            print("Reconnect clicked")
            dispatch_async(dispatch_get_main_queue())
            {
            let netConnections = Connection.isConnectedToNetwork()

                if netConnections == true {
                let netalert = UIAlertView(title: "Internet on line", message: nil, delegate: nil, cancelButtonTitle: "OK")
                netalert.show()

                let url = self.serverLocation + self.onlineLoginApi
                let hashcode = ViewController().getHashcode()

                if(hashcode != "00000") {
                    let url = url + "?hashcode=\(hashcode)"
                    print("url: ", url)
                }

                   ViewController().loadPagelive(url)

                }


            else{
                let netalert = UIAlertView(title: "Internet off line", message: nil, delegate: nil, cancelButtonTitle: "OK")
                netalert.show()
                }
            }
            print("retryConnect end")
            }
        }

Solution

  • You try to perform the loadPagelive(url) on a new instance of your ViewController, not on the current one shown on the screen, that's why you don't see any update.

    You should create a delegate or a completion block in order to execute code on you ViewController instance loaded on the screen: every time you do ViewController(), a new object is created.

    You can try using the delegate pattern, which is simple to achieve. I will try to focus on the important part and create something that can be used with your existing code:

    class ViewController: UIViewController {
        let jsapi = jsapi() // You can use only 1 instance
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Set your ViewController as a delegate, so the jsapi can update it
            jsapi.viewController = self
            login()
        }
    
        func loadPagelive(_ url: URL) {
            // Load page, probably you already have it
        }
    }
    
    class jsapi: NSObject {
        weak var viewController: ViewController?
    
        func retryConnection() {
           // We check if the delegate is set, otherwise it won't work
           guard viewController = viewController else {
               print("Error: delegate not available")
           }
    
           [... your code ...]
    
           // We call the original (and hopefully unique) instance of ViewController
           viewController.loadPagelive(url)
        }
    }