Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.
Before we begin, we assume an understanding of the following things:
iOS and Objective C - intermediate
If you have questions at any point, feel free to comment. We put all the code in our images.
In order to let the rest of our program know that we have the necessary data to move forward, we should trigger an alert in our JS function. The text included after the alert, "weatherDot" is also sent to our callback. This alert will translate into a call to a webview delegate method, although we never plan on displaying an actual alert. We are simply using the alert functionality to suit our callback purposes.
We'll see how this works in detail in the following steps, so for now just understand that setting window.location.href to an alert triggers a delegate method outside of our webview.
Step 2: Creating Our Webview
In order to run JS, we are going to load a script into a web view. We never plan on showing the web view in the foreground, or on using it browse the Internet. Instead, we are going to load a JS string into into the view and run it.
Replace "file text" in the picture above with the scripting you are trying to run. You can hardcode it in, pull it up from a local file, or any other other source, so long as you input a valid JS string. Once you have called the loadHTMLString method with the proper parameters, you are ready to use JS methods!
Step 3: UIWebview Delegate Method
The request parameter will hold data about what the request contains (in this case we can access whatever string we included after our alert in the JS code). The NavigationType parameter will tell us the nature of what triggered the shouldStartLoadRequest method.
Step 4: Identifying the Cause of Function Call
As mentioned before, there are a variety of reasons that this delegate method will be called. We want this code to run if and only if an alert is called, so we need to ensure that the method was not called for another reason. Firstly, we check the navigation type. The JS alert is a UINavigationTypeOther navigation type, so we check for this first. By first checking the navigation type, we can ensure there are no mixups based on other possible standard loads.
Next, we want to make sure that the URL scheme was an alert type. Under the umbrella of UINavigationTypeOther, there are still other types of load requests. Once these conditions are met, we can begin worrying about what we want to do with the alert.
The return values indicate whether or not we want to follow through with the load request. If we return yes, then we will go to an alert screen, and we don't want that. So, in the case of alerts we return no.
Step 5: Now That We Know Our Data Is Ready....
Thanks for reading, and let us know if you have any questions!