Category Archives: Snippet

Inject Javascript functions into a UIWebView

When working with UIWebViews it is often needed to change the appearance of the pages when it is already visible to the user. What if you want give him the possibility to change font or font size?

The answer is the UIWebView method

stringByEvaluatingJavaScriptFromString

And here are some easy examples:

[objc]
-(void)changeFontNameTo:(NSString *)fontName{
NSString *jsFixedString = @”document.getElementsByTagName(‘body’)[0].style”;
NSString *jsString = [[NSString alloc] initWithFormat:@”%@.fontFamily=’%@'”,jsFixedString,fontName];
[self.webView stringByEvaluatingJavaScriptFromString:jsString];
}

-(void)changeFontSizeTo:(NSInteger)fontSize{
//fontSize is in percentage
NSString *jsString = [[NSString alloc] initWithFormat:@”document.getElementsByTagName(‘body’)[0].style.fontSize= ‘%d%%'”, fontSize];
[self.webView stringByEvaluatingJavaScriptFromString:jsString];
}

-(void)changeLineSpacingTo:(NSInteger)lineSpacing{
NSString *jsFixedString = @”document.getElementsByTagName(‘body’)[0].style”;
NSString *jsString = [[NSString alloc] initWithFormat:@”%@.lineHeight=’%d%%'”,jsFixedString,lineSpacing];
[self.webView stringByEvaluatingJavaScriptFromString:jsString];
}

-(void)changeMarginTo:(NSInteger)margin{
NSString *jsFixedString = @”document.getElementsByTagName(‘body’)[0].style”;
NSString *jsString = [[NSString alloc] initWithFormat:@”%@.marginLeft=’%d%%’;%@.marginRight=’%d%%'”,
jsFixedString,margin,jsFixedString,margin];
[self.webView stringByEvaluatingJavaScriptFromString:jsString];
}
[/objc]

For full explanation read also: How To Inject JavaScript Functions Into a UIWebView by Nick Dalton.

Create a Universally Unique IDentifier

Problem: How to get a unique device identifier (i.e. to implement InApp purchasing) without using UDID, banned by Apple.
Solution: In iOS6 we can use identifierForVendor. In prior versions we will use CFUUIDRef. Note that in this case every call of CFUUIDRef creates a new UUID. It is necessary to save the UUID in the device keychain to make it unique.
Read also: Universally Unique IDentifier in iOS5 by Marek Bell
[objc]
+ (NSString *)createLocalUUID {

NSString *localIdentifier;

if ([[UIDevice currentDevice] respondsToSelector:NSSelectorFromString(@”identifierForVendor”)])
// iOS version >= 6
localIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
else {
// iOS version < 6 CFUUIDRef uuidRef = CFUUIDCreate(NULL); CFStringRef uuidStringRef = CFUUIDCreateString(NULL, uuidRef); CFRelease(uuidRef); localIdentifier = [NSString stringWithString:(__bridge NSString *)uuidStringRef]; CFRelease(uuidStringRef); } return localIdentifier; } [/objc]