Objective-C: change text color of UIButton

To change the text color of UIButton is easy. Simply set preferred text color for each state:

[button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
[button setTitleColor:[UIColor yellowColor] forState:UIControlStateNormal];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];

If the text color should state the same in all states, just connect the states with “|”:

[button setTitleColor:[UIColor redColor] forState:(UIControlStateHighlighted | UIControlStateNormal | UIControlStateSelected)];

And remember to change the type of UIButton from “System” to “Custom”. Otherwise the text color gets alpha value in highlighted state.

Objective-C: case insensitive file mapping

File names are case sensitive in iOS. That’s why it is important always to test your app containing file read/write operations not only in simulator, but also on the real iOS devices like iPad or iPhone. In particular situations you get a file name from some configuration file and wonder why NSFileManage cannot find it in the folder where it is contained. This can happen when the name of the file in configuration has a different case than the real file name. Such a special case can be handled by the function below:


+ (NSString*)findCaseInsensitiveFileMappinhForFile:(NSString*)file inFolder:(NSString*)folderPath
{
    
    NSString *result = nil;    
    NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtURL:[NSURL fileURLWithPath:folderPath]
                                          includingPropertiesForKeys:@[NSURLNameKey, NSURLIsDirectoryKey]
                                                             options:NSDirectoryEnumerationSkipsHiddenFiles
                                                        errorHandler:^BOOL(NSURL *url, NSError *error) {
        if (error) {
            NSLog(@"[Error] %@ (%@)", error, url);
            return NO;
        }
        
        return YES;
    }];
    
    for (NSURL *fileURL in enumerator) {
        NSString *filename;
        [fileURL getResourceValue:&filename forKey:NSURLNameKey error:nil];
        NSNumber *isDirectory;
        [fileURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];
        
        // Find same file with different case
        if (![isDirectory boolValue]) {
            if ( [filename caseInsensitiveCompare:file] == NSOrderedSame) {               
                result = filename;
                break;
            }
        }
    }
    return result;
}


Sharing Data between WatchOS app and iOS app

In most cases the WatchKit App you develop has to exchange data with its iOS App. In earlier versions of watchOS it was enough to define an app group to access the same data from the iOS app and from the WatchKit Extension. But since watchOS 3 things have changed. The apps for watchOS became native, i.e. they are natively executed at the Apple Watch. This implies of course changes in the way how the data is exchanged.

Watch Connectivity Framework is the way Apple provides to synchronize data with WatchOS Apps.

If your existing Watch app and iOS app use a shared group container or iCloud to exchange data, you must change the way you exchange that data in watchOS 2. Because the WatchKit extension now runs on Apple Watch, the extension must exchange data with the iOS app wirelessly. You can do that using an NSURLSession object or using the Watch Connectivity framework, which supports bidirectional communication between your iOS app and WatchKit extension.

To see a corresponding session click here: WWDC 2015 – Session 713 – watchOS

I could also recommend an excellent tutorial/overview for beginners: watchOS 2: How to communicate between devices using Watch Connectivity

Short summary of the most important things about Watch Connectivity Framework:

  • Two separate stores have to be maintained. There is no automatic way for Core Data data to be synchronized with the watch app
  • There are two communication categories: Background transfers and Interactive messaging
  • Background transfers can be: Application context, User Info Transfer and File transfer. Application context is always overridden by the latest data when waiting in the transfer queue. User Info realizes FIFO principle, i.e. all data in the queue will be delivered. File transfer is self explaining.

 

 

iOS Architecture Patterns

Developing sophisticated apps is every time a challenge to find a proper way to provide scalability, testability, enable minimal maintenance cost. Without utilization of design patterns and suitable software architecture development process can get to a nightmare very quickly. Not only for the developer, but also for the customer. Of course, there is no general recommendation for utilization of this or that architecture pattern. It depends on particular requirements and expectations. The most popular architecture patterns are MVC, MVP, MVVM, VIPER etc. These patterns and their realization for iOS are discussed in a great article. Especially, advantages and disadvantages regarding testability and development overhead are discussed their. Comments are also worth reading!

HTTPS request with self signed certificate in iOS 10.3

iOS 10.3 seems to handle self signed certificates different then iOS 10.2. Even with the option NSAllowsArbitraryLoads enabled the request fails with the error:

The certificate for this server is invalid. You might be connecting to a server that is pretending to be “Domain name” which could put your confidential information at risk.

To fix the issue install the self signed certificate as usual. Afterwards go to

Settings -> About -> Certificate Trust Settings

and just enable the Full Trust for your root certificate.

WKWebView. Return a value from native code to JavaScript

WKWebView exposes a comfortable way to call native code from JavaScript. So called Message handlers are defined in native code and can be later used in JavaScript like this:

webkit.messageHandlers.pushMessage(message)

But what about return values? For as you know, WKWebView runs in its own process and that’s why pushMessage() function cannot return any value. It is not possible to get the return value from native function synchronously. It is also not possible to give a JS callback function to native function. So what to do, if we need a return value from native function?

[adinserter block=”1″]

There are several approaches how to realize and organize asynchronous communication of native code <-> JavaScript with WKWebView. The first thought is to implement another JS function that would be called from native code after operation on native side is finished, i.e.

JavaScript code:


function readStringFromFile(relativeFilePath) {
webkit.messageHandlers.readFileHandlder.pushMessage({filePath: relativeFilePath});
}

// this function will be later called by native code
function readStringFromFileReturn(returnedValue) {
// do you stuff with returned value here
}

And the corresponding handler implementation in Objective-C would look like this:

- (void)userContentController:(WKUserContentController*)userContentController
didReceiveScriptMessage:(WKScriptMessage*)message {

if([message.name isEqualToString:@"readFileHandler"]) {
NSDictionary *paramDict = message.body;
NSString *filePath = [paramDict objectForKey:@"filePath"];
NSString *resultString = [self readStringFromFileSynchronously: filePath];
NSString *javaScript = [NSString stringWithFormat:@"readStringFromFileReturn('%@');", resultString];
[self.webView evaluateJavaScript:javaScript completionHandler:nil];
}
}

The described approach is not very elegant. If you have several functions in your interface between JavaScript and native code, the chained calls get very quickly confusing.

Much better approach is utilizing relative new concept of promises in JavaScript. I think, it’s also the way, Apple bore in mind when WKWebView has been introduced. More about promises can be read here or here. First, we need to extend our JavaScript:


// object for storing references to our promise-objects
var promises = {}

// generates a unique id, not obligator a UUID
function generateUUID() {
var d = new Date().getTime();
var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = (d + Math.random()*16)%16 | 0;
d = Math.floor(d/16);
return (c=='x' ? r : (r&amp;amp;amp;amp;amp;amp;0x3|0x8)).toString(16);
});
return uuid;
};

// this funciton is called by native methods
// @param promiseId - id of the promise stored in global variable promises
function resolvePromise(promiseId, data, error) {
if (error){
promises[promiseId].reject(data);

} else{
promises[promiseId].resolve(data);
}
// remove referenfe to stored promise
delete promises[promiseId];
}

Our readStringFromFile function looks now like this:


function readStringFromFile(relativeFilePath) {
var promise = new Promise(function(resolve, reject) {
// we generate a unique id to reference the promise later
// from native function
var promiseId = generateUUID();
// save reference to promise in the global variable
this.promises[promiseId] = { resolve, reject};

try {
// call native function
window.webkit.messageHandlers.readFileHandler.postMessage({promiseId: promiseId, fileName: fileName});
}
catch(exception) {
alert(exception);
}

});

return promise;

}

The JavaScript code is self explaining. One important thing to mention is that the reference to the created promise-object is stored globally.

And now the Objective-C code:

- (void)userContentController:(WKUserContentController*)userContentController
didReceiveScriptMessage:(WKScriptMessage*)message {

if([message.name isEqualToString:@"readFileHandler"]) {
NSDictionary *paramDict = message.body;
NSString *promiseId = [paramDict objectForKey:@"promiseId"];
NSString *filePath = [paramDict objectForKey:@"filePath"];
NSString * resultString = [self readStringFromFileSynchronously: filePath];
NSString *javaScript = [NSString stringWithFormat:@"resolvePromise('%@',%@, null);",promiseId, resultString];
[self.webView evaluateJavaScript:javaScript completionHandler:nil];
}
}

As you can see the native function calls resolvePromise with return value. The code at JavaScript continues running, after the promise is resolved. What we are still missing, is the usage example for function readStringFromFile, which returns a promise object:


readStringFromFile("someRelativePath").then(function(returnedString) {
var returnValue = returnedString;
logToConsole(returnValue);
// do your stuff here

}, function(returnedString) {
logToConsole('error');
});

Utilization of promises as described above makes code more readable.It allows a clean definition of the interface between JavaScript and native code.

There are also other projects, aiming to enable easy communication between JavaScript in WKWebView and native code, e.g. XWebView. However, when integrating such components in your project be aware of:

  • you become dependent on third party development. Each newer version of SWIFT would make you to wait for compatible updates
  • they use the same messaging mechanism under the hood

About communication between JavaScript and native code in WKWebView

WKWebView is a replacement of UIWebView that is available since iOS 2.0. Apple encourages using WKWebView instead of UIWebView in its documentation:

Note

In apps that run in iOS 8 and later, use the WKWebView class instead of using UIWebView.

One of the key advantages of the new component is the more comfortable way to call native functions directly from JavaScript and to execute JavaScript functions at the native side. However, there are some limitations, which one should know:

  • WKWebView runs in its own process. On one hand it is a great performance improvement. On the on the hand it implies some unpleasant limitations in exchanging data between native app and the WKWebView
  • Native <=> JavaScript communication can only be asynchronous.
  • Native functions called from JavaScript cannot return values immediately.
  • The only way to return a value is to call another JavaScript function from native function with return value as parameter.
  • JavaScript functions can be called within native native methods only in global context.

To my opinion, limitations mentioned above are a step back comparing with UIWebView. With UIWebView it is possible to obtain JavaScript context and inject native(!) objects into that context by means of JSExport interface. There is then no difference wether you call a function on an injected object or some other JS function. Native functions can return values synchronously! The only disadvantage of this approach is that Apple has not exposed JavaScript context of the UIWebView officially. It is only possible to obtain the context  via private properties. That’s why this approach should not be used in product apps.

Start using Swift code in your Objective-C project

If you decided to start using Swift in your existing Xcode project, it can become a pain if your project is large and contains multiple targets. Follow steps below to be able to use Swift classes in your Objective-C code:

  1. Create a new *.swift file in your Objective-C project, or drag a .swift file with Finder
  2. Xcode prompts you to create an Objective-C bridging header file. Confirm it or add the bridging header manually
  3. Use @objc attribute for your Swift class:
    import Foundation
    
    @objc class YourController: UIViewController {    
    }
    
    
  4. In Build Settings of your project check parameters below:
    Defines Module : YES
    Install Objective-C Compatibility Header : YES => Once you’ve added *.swift file to the project this property will appear in Build Settings
    Objective-C Generated Interface Header : $(PROJECT_NAME)-Swift.h
  5. Import Swift interface header in your *.m file like this:
    #import "YourProject-Swift.h" // $(PROJECT_NAME)-Swift.h
    

iOS: Today Extensions / Widgets

A Today extension, also known as a widget, is a way for the app to provide quick access to its main functions and the up-to-date information in the Notification Center. The content for the widgets might be directly fetched from the web, but quite often there is a requirement to share data between the App and its widget.

How to add Today extension / Widget to an existing project?

Just add a new target of type “Today extension” to your project . To debug/start Today extension just select the proper target and run.

Can the same code, e.g. views and controllers, be shared/utilized between Widget and App targets?

Yes. Be sure to select checkboxes for the corresponding files in the “Target Membership” window of the Xcode. There are, however, some limitations, especially using swipe gestures. The swipe gesture triggers swiping between the Today and Notifications sections within Notification Center, so it doesn’t really provide the best or most reliable user experience.

What about CoreData in Widgets?

No problem, almost.. In general, by default, an App and its extension cannot access the same data, since their security domains are different. In order to solve this problem there should be created an App Group. An App Group provides a shared bundle that can be used by the app and its extensions as a shared container in which data can be stored. The App group can be configured in the apple developer portal (s. nice tutorial) or directly in Xcode under target capabilities.

Read More