July 17, 2014

Objective-C WKWebView to JavaScript and Back

Posted in iPhone development, mac development tagged , , , , at 4:50 pm by tetontech

 In a previous post I showed how to communicate from JavaScript to Swift and back.  This code example shows how to use the new WKWebView rather than the old UIWebView with Objective-C.

Since WKWebView doesn’t yet show up as a drag-and-droppable view in Interface Builder, and other IB work-arounds cause the app to crash, a WKWebView instance is created in the ViewController’s viewDidLoad method. The WKWebView instance is then sized to fill the entire view of the device. This can cause usability problems since the WKWebView’s content now overlaps the header bar. If I was creating an app to ship, I would use Interface Builder to add a UIView, create an IBOutlet to that view, and size the UIView to fit the display portion of the screen. I would then add the WKWebView to the UIView I added using Interface Builder.

The header file for the ViewController class shows how to include the WebKit headers and make the ViewController a WKScriptMessageHandler. The ViewController needs to be a WKScriptMessageHandler since, in this example, the ViewController is going to be sent messages from the JavaScript code.

#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
@interface ViewController : UIViewController <WKScriptMessageHandler>
   
@end

In order to create the WKWebView and add it to the main view in viewDidLoad and later use the same WKWebView in userContentController:didReceiveScriptMessage method a WKWebView property called theWebView is added to the ViewController class.

The ViewController’s viewDidLoad method includes the creation of an instance of WKWebViewConfiguration. Among other things, WKWebViewConfiguration is used to setup and name the JavaScript message listener. This setup is done with the WKWebViewConfiguration userContentController’s addScriptMessageHandler:name method. For this example I’ve chosen ‘interOp’ as the name to be exposed to JavaScript for the message handler and used the ViewController as the message handler.

Once WKWebKit is debugged, the following code should work. It currently doesn’t (iOS 8.1) so I’ll show you a work-around right after this “is supposed to work but doesn’t code example.”

#import "ViewController.h"

@interface ViewController ()
    @property(strong,nonatomic) WKWebView *theWebView;
@end

@implementation ViewController
            
- (void)viewDidLoad {
    [super viewDidLoad];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSURL *url = [NSURL fileURLWithPath:path];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    WKWebViewConfiguration *theConfiguration = 
          [[WKWebViewConfiguration alloc] init];
    [theConfiguration.userContentController 
          addScriptMessageHandler:self name:@"interOp"];
    
    _theWebView = [[WKWebView alloc] initWithFrame:self.view.frame 
                      configuration:theConfiguration];
    [_theWebView loadRequest:request];
    [self.view addSubview:_theWebView];
    
}

Since ViewController is a WKScriptMessageHandler, as declared in the ViewController interface, it must implement the userContentController:didReceiveScriptMessage method. This is the method that is triggered each time 'interOp' is sent a message from the JavaScript code.
- (void)userContentController:(WKUserContentController *)userContentController 
                            didReceiveScriptMessage:(WKScriptMessage *)message{
    NSDictionary *sentData = (NSDictionary*)message.body;
    long aCount = [sentData[@"count"] integerValue];
    aCount++;
    [_theWebView evaluateJavaScript:[NSString 
            stringWithFormat:@"storeAndShow(%ld)", aCount] completionHandler:nil];
}

In the example code above you can see a WKScriptMessage is received from JavaScript. Since WKWebKit defines JSON as the data transport protocol, the JavaScript associative array sent as the message's body has already been converted into an NSDictionary before we have access to the message. We can then use this NSDictionary to retrieve an int that is the value associated with the 'count' label. The JSON conversation creates NSNumbers for numeric type values so the code example retrieves the NSNumber's intValue, modifies it, and then sends the modified value back to JavaScript. 

One of the very nice features of WKWebKit framework is that the WKWebView runs independently of the main, or User Interface, thread. This keeps our apps responsive to user input. The storeAndShow method will not execute in the app's main thread. 

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

The JavaScript examples below show how to send a message to Objective-C using webkit’s list of messageHandlers and the interOp handler we setup in the ViewController’s viewDidLoad method. An example of this is found in the sendCount JavaScript function. The storeAndShow function that is triggered is strait forward. All that function does is some standard JavaScript using the DOM (Document Object Model).

var count = 0

function sendCount(){
    var message = {"count":count}
    window.webkit.messageHandlers.interOp.postMessage(message)
}

function storeAndShow(updatedCount){
    count = updatedCount
    document.querySelector("#resultDisplay").innerHTML = count
}

Overall I am really pleased with the new WKWebView and the other classes in the WKWebView framework when it is compared to the old UIWebView. I like the WKWebView executing outside the main thread. I like the choice of JSON for the data transfer protocol. The adding of the message handlers is a little awkward, but nothing is ever perfect.

When you try to run this “should work but doesn’t code” the screen on your device will be blank. There is a scrollbar that you can move but the page is never displayed. This code does work on a device when written in Swift if you move all of the web components to the app’s temp directory before you build the NSURL. For the work-around we’ll do the same thing in Objective-C. I’ve written a small Objective-C class called WebMover to do that for you. It will move web files and any of you app’s web directories for you. When it does the move it will return the path to the index.html file to you so you can use it to create a NSURL. I won’t cover that code in this posting. You can get WebMover’s source and an example project from my gitHub ObjectivelyHybrid repo.

I have tracked down one of the issues that causes Objective-C to fail to load the page, even when the web files have been copied to the app’s temp directory. The problem is with this line of code.

NSURL *url = [NSURL fileURLWithPath:path];

If this line of code is executed, a NSURL is generated and appears to be good in all observable respects. The NSURL is defective. If the same line of code is executed in Swift, the defect disappears. Because of this, the work-around will generate the NSURL in Swift, but the rest of the code will remain Objective-C.

The working viewDidLoad method now looks like this.

@implementation ViewController
            
- (void)viewDidLoad {
    [super viewDidLoad];
    NSError *moveError = nil;
    //modify the array of file types to fit the web file types your app uses.
    NSString *indexHTMLPath = [WebMover moveDirectoriesAndWebFilesOfType:
                               @[@"js",@"css",@"html",@"png",@"jpg",@"gif"] error:&moveError];
    if (moveError != nil) {
        NSLog(@"%@",moveError.description);
    }
    //this is an Objective-C call to some Swift code.
    NSURL *url = [SwiftlyBridge buildURL:indexHTMLPath];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    WKWebViewConfiguration *theConfiguration = 
          [[WKWebViewConfiguration alloc] init];
    [theConfiguration.userContentController 
          addScriptMessageHandler:self name:@"interOp"];
    
    _theWebView = [[WKWebView alloc] initWithFrame:self.view.frame 
                      configuration:theConfiguration];
    [_theWebView loadRequest:request];
    [self.view addSubview:_theWebView];
    
}

The thing I like about this work-around is how close it is to the original “should work” solution. Unlike others who have suggested highly complicated things like building a web server into your app.

The SwiftlyBridge Code is also tiny. In the example project you can find it in the SwiftlyBridge.swift file.

import Foundation
import WebKit

@objc class SwiftlyBridge {
    
    class func buildURL(indexHTMLPath:String) ->NSURL{
        return NSURL(fileURLWithPath: indexHTMLPath)!
    }
}

When you add this file to your project, Xcode will ask you if you want it to create a bridging header file. The answer is an emphatic YES. Make sure you have it do this for you.

Once you’ve added the WebMover.m and .h files and the SwiftlyBridge.swift file maker SURE that you attempt to build your project. It will fail, but the build process will generate a .h, header, file for you that will allow you to import the SwiftlyBridge class. In the example project this generated header file is imported in to the view controller source, you can compile and run.

The name of the generated header is always <ProjectName>-Swift.h. The Example project’s name is ObjectivelyHybridiOSExample so the import call is

#import <ObjectivelyHybridiOSExample-Swift.h>

I’ve had trouble with projects that have spaces or dashes in there names. In those cases Xcode doesn’t seem to be able to find the generated header file.

 

That should do it. Post if you are having issues.

July 15, 2014

Swift to JavaScript and JavaScript to Swift. A round trip.

Posted in Uncategorized tagged , , , , , at 9:12 pm by tetontech

Edit: Since originally writing this post I have Created the SwiftlyHybrid and AndyHybrid libraries and put them on gitHub. If you are interested in the topic discussed here I would suggest also reading the SwiftlyHybrid and AndyHybrid follow up posting.

In a previous post I showed how to make a call from JavaScript to Swift. Take a look there for a more in-depth discussion of the code to accomplish that data transfer. This example expands on what I did in that post by showing how to make a call from JavaScript to Swift, do a calculation, and then pass the results back to JavaScript. The source code is very similar. It uses one method, evaluateJavaScript(), of the WKWebView class that wasn’t available in Apple’s previous Swift beta.

In the view controller’s userContentController method we’ll need to have access to the WKWebView created in the viewDidLoad method. This requires the addition of a WKWebView attribute to the ViewController class. After trying a couple of experimental ideas I remembered the correct, Swifty way to do this. I couldn’t create the WebView on the same line as the attribute was declared since the initializer for the WKWebView isn’t as simple as adding some integer attribute (var someInt = 3). Instead the initializer needs a frame and a WKWebViewConfiguration. Because of this the WKWebView must be initialized in the viewDidLoad method (This may change if Apple adds a WKWebView to Interface Builder).

The Swift way to declare an attribute and initialize it in something other than an init method is to make the attribute optional using the ? operator.

class ViewController: UIViewController, WKScriptMessageHandler {
    
    var theWebView: WKWebView?
}

In the viewDidLoad method the WKWebView can now be created using the WKWebView function. Once theWebView has been set, the ! operator is needed to declare that we know theWebView attribute is not nil.

(Warning: the functionallity of WKWebView has changed since this code was written. You must move all resources (html, JavaScript, Css, images, and other files) into the temp directory or WKWebView will not load the resources. This may change in the future as WebKit changes or it might not.)

    override func viewDidLoad() {
        super.viewDidLoad()
        var path = NSBundle.mainBundle().pathForResource("index", 
                               ofType: "html")
        var url = NSURL(fileURLWithPath: path)
        var request = NSURLRequest(URL: url)

        var theConfiguration = WKWebViewConfiguration()
        theConfiguration.userContentController.addScriptMessageHandler(self, 
                                   name: "interOp")

        theWebView = WKWebView(frame: self.view.frame, 
                             configuration: theConfiguration)
        theWebView!.loadRequest(request)
        self.view.addSubview(theWebView)

    }

As in the previous example, the userContentController() method must be implemented to handle the messages captured by the script message handler that was added to theConfiguration. In this example the message’s body, the data sent from the JavaScript is interpreted as an NSDictionary since the JavaScript sends an associative array.

    func userContentController(userContentController: 
       WKUserContentController!,
       didReceiveScriptMessage message: WKScriptMessage!) {
        
        let sentData = message.body as NSDictionary
        let aCount:Int = Int(sentData["count"] as NSNumber)
        
        theWebView!.evaluateJavaScript("storeAndShow( \(aCount + 1) )", 
                                        completionHandler: nil)
    }

The other change to the previous example is the addition of the call to theWebView’s evaluateJavaScript method. It has two parameters; a string that is the Javascript to be executed, and a function or closure that will be notified once the JavaScript completes. In this example I don’t need to know when the JavaScript completes so I passed nil as the second parameter.

The javascript for this example is strait forward; an onclick listener function to send a message to the Swift message handler, and the storeAndShow function that the Swift code will call to send a message back to the JavaScript.

var count = 0

function sendCount(){
    var message = {"count":count}
    window.webkit.messageHandlers.interOp.postMessage(message)
}

function storeAndShow(updatedCount){
    count = updatedCount
    document.querySelector("#resultDisplay").innerHTML = count
}

For my own code I would send a Dictionary back to the JavaScript where it would be used as an associative array. I left that out of this example since I didn’t think it was necessary to show.

Overall, the interaction between Swift and Javascript using the WKWebView is more strait forward than using the old UIWebView. It is nice to have a JavaScript way to directly call to Swift. I also like the selection of JSON as the data transfer format for the JS to Swift communication. It reflects the decision I made to adopt that format for QCHybrid years ago. It would be better if the values in the dictionary knew their type so casting using the as operator wasn’t needed but I can live with it the way it is.

July 7, 2014

Swift, C libraries, and a Speed Test

Posted in iPhone development, mac development tagged , , , , , , , , , at 7:20 pm by tetontech

In a previous post I showed how to statically link a C library into a Swift app. I mentioned in that posting that converting data for use in libraries written in other languages can be costly. I have done some testing by passing 3 basic data types between Swift and C. The results are very interesting and not what I would have predicted based on calling C functions from other languages I’ve used.

The three types I tested were Ints, Doubles, and Strings. I did the test by calling an echo function for each type in both Swift and C. I supposed that calling the C echo function would be slower that calling the Swift echo function in each case. This was not so. It was faster to convert a Swift Int to a c int, pass it to a C function, and then convert the returned C int into a Swift Int than to call the Swift echo function that required no conversion. The difference was not huge, around 300 milliseconds for 100,000,000 calls, but it was consistent.

Doing conversions for Doubles, passing them to a C function, and converting the resultant c double to a Swift Double was also faster than calling a Swift function that echoed a Swift double it was passed. Once again the difference was not huge. There was around an 80 millisecond difference.

The Swift String to char* conversion is messy so I figured converting a Swift string and passing a char*  would be slow. It was so slow that I reduced the number of function calls I was timing to 1,000,000. Making that many calls it was around 12 times slower to convert a Swift String to a char*, pass the char* to C, and convert the resultant char* back to a Swift String.

So what conclusions do I draw? The compiler is currently optimizing C calls requiring number conversions slightly more effectively than the Swift calls. Because of this, if all I’m passing are simple things like Ints and Doubles I can go ahead and use C libraries without much concern. If I’m passing more complex things like Strings or Structs, I would avoid using them in C calls when possible.

Here is the code for the Swift and the C echo functions.

    //Swift
    func doSwiftIntStuff(anInt:Int) -> (Int){
        return anInt
    }
    func doSwiftDoubleStuff(aDouble:Double) -> (Double){
        return aDouble
    }
    func doSwiftStringStuff(aString:String) -> (String){
        return aString
    }
    //C
    int doIntStuff(int anInt){
        return anInt;
    }

    char* doStringStuff(char* aStr){
        return aStr;
    }

    double doDoubleStuff(double aDouble){
        return aDouble;
    }

Here is an example of converting and passing a Swift Int

    var initialTime = NSDate()
    let aNum = 3
    for index in 0..100_000_000 {
        let aResult = Int(doIntStuff(Int32(aNum)))
    }
    println("Swift result C int: \(initialTime.timeIntervalSinceNow)")

Here is an example of converting and passing a Swift String. Notice that this example will only handle ASCII strings.

initialTime = NSDate()
for index in 0..1_000_000 {
    var ascii = aString.dataUsingEncoding(NSASCIIStringEncoding, 
                allowLossyConversion:true)
    var stringAsChars = CChar[](count:ascii.length, repeatedValue:CChar(0))
    ascii.getBytes(&stringAsChars, length:ascii.length)
    stringAsChars.append(CChar(0))
    let aResult:String = String.fromCString(doStringStuff(&stringAsChars))
}
println("Swift result C string: \(initialTime.timeIntervalSinceNow)")

July 3, 2014

Swift and Statically Linking C libraries

Posted in iPhone development, mac development tagged , , , , at 5:26 pm by tetontech

In preparation for creating a simulation engine more robust and current than the simple one I described in a previous post I decided to do some sandboxing of how to statically link and use an existing C library.

Rather than use something complex I created a simple C library that has one function, doStuff. This function is declared in the StuffStatic.h header file

//
//  StuffStatic.h
//  StuffStatic
//

int doStuff(int anInt);

 

and defined in the StuffStatic.c implementation file.

//
//  StuffStatic.c
//  StuffStatic
//

#import <stdio.h> 
#import "StuffStatic.h"

int doStuff(int anInt){
    int result = anInt * 2;
    printf("the result is %d\n",result);
    return result;
}

This code was compiled into libStuffStatic.a.

To use this library in a Swift app I added the libStuffStatic.a file and the StuffStatic directory containing the StuffStatic.h file to the project by dragging them into the Supporting Files group.

Interestingly, Xcode didn’t ask if I wanted to add the bridging header file I knew would be needed to make the C calls from within Swift. Rather than go through the process of manually adding a bridging file I used Xcode to create a junk.c file. This triggered the creation of the bridging header file and made all of the changes to the project required to use it. I then deleted the junk.c file from my project.

The bridging header file is used to do an import of the header files for the library. Any header from the library you include in this file automatically makes available anything defined in it to Swift. Because of this you can make calls to the functions in the header files directly in any Swift file without worrying about doing an include statement.

Since my swift project was just a sandbox project I decided to use the doStuff function directly in the ViewController’s viewDidLoad method. I wanted to simulate a number being calculated in Swift, passed to C, and a returned C int being used in Swift.

override func viewDidLoad() {
        super.viewDidLoad()
        let aNum = 3
        let aResult = Int(doStuff(Int32(aNum)))
        println("Swift result: \(aResult)")
    }

Xcode won’t do autoboxing for us so we have to do it ourselves. To convert the Swift Int aNum to a C int I passed aNum to the Int32 constructor. doStuff could then use it directly. Since doStuff returns a C int I passed its result to Swifts Int constructor and stored the new Swift Int in the aResult constant.

When data types are bridged between languages there is a computational speed cost. I haven’t yet tested what this cost is for Swift-to-C and C-to-Swift bridging. That is on my plate for next week.

%d bloggers like this: