Localize iOS app at runtime.

Hello again,

This tutorial will show you how to localize your app at run-time, please feel free to check an example in github/iOS-Localization.

First of all, download the Language.h/m class from the repository and add them to your project.

  • after that import the Language.h to your class like this:

#import “Language.h”

  • In your appDelegate, set your startup language like this:

[Language setLanguage:@”en”];

  • Create a localize string file that contain all your strings localized depending on the languages you choose.(Please check the example in the repository).
  • To get the string based on the selected language, use the method in the Language class:

[Language get:@”title” alter:@”title not exisit”];

That’s it, for more understanding of how to do this clearly, please check the example in the github.

Thank you and stay tuned for more tutorials soon.

How to call an objective-c method from JavaScript

As the title says, call an objective-c method from Javascript/HTML file. Let’s talk about the Javascript side, we have to request a new URL with a specific string and this is done in Javascript side by

function communicateWithObjectiveC () {

window.location = “js-call:myObjectiveCFunction:” + names;

}

This will make the UIWebView call a delegate method, which is :

– (BOOL)webView:(UIWebView *)webView

shouldStartLoadWithRequest:(NSURLRequest *)request

navigationType:(UIWebViewNavigationType)navigationType {

In this method, we can search the new request string by using:

if ([[[request URL] absoluteString] hasPrefix:@”js-call:”]) {

after that, we call the method that we want by:

[self performSelector:NSSelectorFromString(function)];

If we wrap up the previous codes (Objective-c side), the method will look like this:

– (BOOL)webView:(UIWebView *)webView

shouldStartLoadWithRequest:(NSURLRequest *)request

navigationType:(UIWebViewNavigationType)navigationType {

// Intercept custom location change, URL begins with “js-call:”

if ([[[request URL] absoluteString] hasPrefix:@”js-call:”]) {

NSString *requestString = [[request URL] absoluteString];

// Extract the selector name from the URL

NSArray *components = [requestString componentsSeparatedByString:@”:”];

if ([[components objectAtIndex:1] isEqualToString:@”myObjectiveCFunction”]) {

NSString *function = [components objectAtIndex:1];

// Call the given selector

[self performSelector:NSSelectorFromString(function)];

}

// Cancel the location change

return NO;

}

// Accept this location change

return YES;

}

That’s it, piece of cake 🙂

If there is any ambiguity, don’t be shy, just ask.

Be tuned for the next Tutorial.