Coding Power Unleashed
Programming blogs containing .NET, C#, LINQ, Objective-C and Delphi experiences
Sunday, February 03, 2013
Use an image as your UIBarButtonItem
Monday, February 06, 2012
Xcode snippet #3: Injecting JavaScript in UIWebView
(Xcode's webbrowser counterpart)
Doing this in JavaScript is an easy task. All we have to do is to inject a JavaScript function into the loaded webpage which will do the work for us.
Injecting JavaScript into an UIWebView control can be achieved using the stringByEvaluatingJavaScriptFromString method, which returns the result of a given script. In other words you can run scripts with this method.
In the below example all links from a webpage are extracted and returned as string formatted as href|text|title.
-(void)getHyperlinks { [webView stringByEvaluatingJavaScriptFromString:@"var script = document.createElement('script');" "script.type = 'text/javascript';" "script.text = \"function getHyperlinks() { " "var links = document.getElementsByTagName('a');" "var allLinks = '';" "for (var i = 0; i<links.length; i++) {" "var link = links[i].href + '|' + links[i].text + '|' + links[i].title + ';';" "allLinks += link;" "} return allLinks;" "}\";" "document.getElementsByTagName('head')[0].appendChild(script);"]; NSString *html = [webView stringByEvaluatingJavaScriptFromString: @"getHyperlinks();"]; textView.text = html; }In the first step the JavaScript function getHyperlinks() is injected in the HTML document. At last the function is executed and its result is returned into a textview.
That's all!
Sunday, September 18, 2011
Xcode snippet #2: Archiving objects with NSKeyedArchiver
Step 1: Comply with the NSCoding protocol
The first thing we have to do is to let our object comply with the NSCoding protocol. This protocol adds encoding and decoding methods to our object. Complying is easily done by adding
@interface Settings : NSObject<NSCoding> { }Step 2: Implement the encodeWithCode and initWithCoder methods
We have to tell the NSKeyedArchiver object how our object should be encoded. Simply said tell it what our properties are and what types they are etc.
This is done the encodeWithCoder method (as implemented by the NSCoding protocol), here under you see an example for an object, boolean and int property.
- (void)encodeWithCoder:(NSCoder *)coder { [coder encodeObject:self.name forKey:@"name"]; [coder encodeBool:self.newsLetter forKey:@"newsLetter"]; [coder encodeInt32:self.count forKey:@"count"]; }
To unarchive our object we have to implement the initWithCoder method: (Make sure that the keys in both the encodeWithCoder and initWithCoder are the same for each property)
-(id)initWithCoder:(NSCoder *)coder { if ((self = [super init])) { self.name = [[coder decodeObjectForKey:@"name"] retain]; self.newsLetter = [coder decodeBoolForKey:@"newsLetter"]; self.count = [coder decodeInt32ForKey:@"count"]; } return self; }That is pretty much all we have to do before we can archive and unarchive.
Step 3: Implement the archive and unarchive methods
What is left is to make two methods for un- and archiving. The saveSetting methods has two parameters, namely settings, the object to archive and the name for the file we want to save it to. With help of the getFullFilePath method we get a full file path to the Document directory of our device. To bring our object back to live use the loadSettings method.
-(NSString*) getFullFilePath:(NSString*)name { NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *savePath = [paths objectAtIndex:0]; NSString *theFileName = [NSString stringWithFormat:@"%@.setting", name]; return [savePath stringByAppendingPathComponent: theFileName]; } -(void)saveSetting:(Settings *)settings name: (NSString *)name { NSString *filePath = [self getFullFilePath:name]; NSData *theData = [NSKeyedArchiver archivedDataWithRootObject:settings]; [NSKeyedArchiver archiveRootObject:theData toFile:filePath]; } -(Settings*)loadSetting:(NSString *)name { NSString *filePath = [self getFullFilePath:name]; NSData *theData = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath]; Settings *settings = [NSKeyedUnarchiver unarchiveObjectWithData:theData]; return settings; }Saving arrays of objects
It is also very easy to save lists of objects to file. Suppose we have a list with Settings and want to store them in one file. You can achieve this by archiving a NSMutableArray. For example:
// Archiving NSMutableArray *array = self.self.settingsList; [NSKeyedArchiver archiveRootObject:array toFile: [savePath stringByAppendingPathComponent: theFileName]]; //UnArchiving NSMutableArray *array = [NSKeyedUnarchiver unarchiveObjectWithFile: [savePath stringByAppendingPathComponent: theFileName]]; if ([array count] > 0) { self.settingsList = array; }
Conclusion, the NSKeyedArchiver and NSKeyedUnarchiver are pretty easy and straight forwarded to use for persisting objects. It is very handy for saving small objects likes settings etc.
More information:
NSKeyedArchiver Class Reference
NSCoding protocol reference
Monday, April 04, 2011
Xcode snippet #1: Reading the contents of a directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsPath = [paths objectAtIndex:0]; NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsPath error:nil]; for (NSString *dir in dirContents) { if ([dir hasSuffix:@".list"]) { NSRange range = [dir rangeOfString:@"."]; NSString *name = [dir substringToIndex:range.location]; if (![name isEqualToString:@""]) { MyListItem *listItem = [[MyListItem alloc] init]; listItem.name = name; [lists addObject:listItem]; [listItem release]; } } }
Wednesday, October 27, 2010
Developing for the iPad
I can tell you that developing for the iPad is a total different experience compared to Delphi and Visual Studio. Never the less it is great fun! Besides the fact that it is a fun platform to work on it is even more fun to learn a new platform, language and IDE.
The tools: XCode and Interface builder
We decided to go the hard way and develop with Apples native IDE XCode. As .NET developer an easier approach would be to choose for a Mono solution like MonoTouch, however we felt that we had to know 'the metal' first.
The main tools you use developing for iPad are XCode and Interface builder. XCode is a good to work with IDE, however compared to Visual Studio it lacks some features. (Must say I still find new features, even today). One annoying point of XCode is that it opens every file in a new window (when double clicking on a file) so after a while it can be hard to seperate the trees from the forest with all that open files. However if you click once you can keep them in one window but for some reason that is hard to persist.
A big plus for XCode, in my opinion, is that it helps you to work in the MVC design pattern way which gives you clean code.
XCode does not offer an integrated form designer like VS does instead you make your views (forms) with Interface builder.
The language Objective-C
The language, Objective-C, looks at first very weird with all that brackets but there are great resources online that helped us to get started.
If you would like to start iPad development take a look at some resources we gathered along the way:
Apples developer website (Get yourself a free account)
Stanford University lectures on iTunes U (Highly recommended!!!!)
Cocoa Dev Central - Learn Objective-C
It is likely that I will write some more blogposts about this new adventure in the future.
Tuesday, August 17, 2010
Fooling around with TWebbrowser compilation post
In the statistics of my blog I find a lot of people searching for Delphi’s TWebbrowser solutions and examples. I wrote a few post about some TWebbrowser specific problems and possible solutions.
Because they are in seperated, non related, posts I thought it would be nice to compilate all the knowledge in one blogpost. Well here it is. :)
Fooling around with TWebbrowser #1
Describes how to use TWebbrowser for editing HTML
Fooling around with TWebbrowser #2
Describes how to retain the browser session within you application
Describes some TWebbrowser basics like how to get the right popwindowsize, how to fill up a combobox with visited websites, how to enable/disable navigate buttons etcetera.
Fooling around with TWebbrowser #4
Describes two solutions for the Enter key problem.
Posting data with TWebbrowser
Describes how to post data to websites using TWebbrowser
Saving TWebbrowser content with IPersistFile
Describes two ways to save the content of the current loaded document in the browser.
Two way interaction with Javascript in Winforms using Webbrowser
Although about Winforms C# this should be compatible with Delphi TWebbrowser.
Enjoy!
Wednesday, May 19, 2010
Using Extension methods on Lists to make it fluent
Since C# 3.0 you can write extension methods on any class that you want, even if you don’t have the source code of the class. In other words you can extend a class with your own methods.
Extension methods can only be declared in static classes as static methods.
Extensions on List<T> classes can be very handy and make your code more readable and fluent.
Suppose you have this mixed Animal list with Dogs and Cats from this blogpost.
List<Animal> animalList = new List<Animal>();
animalList.Add(new Dog("Dog1", ConsoleColor.Red));
animalList.Add(new Dog("Dog2", ConsoleColor.Green));
animalList.Add(new Dog("Dog3", ConsoleColor.Red));
animalList.Add(new Cat("Cat1", ConsoleColor.Black));
animalList.Add(new Cat("Cat2", ConsoleColor.Black));
animalList.Add(new Cat("Cat3", ConsoleColor.Black));
(Never mind the ConsoleColor for the animal ;-) )
Suppose we want all the red dogs from the animalList, we could write our code like:
//Get the Red docs
List<Dog> redDogList = animalList.OfType<Dog>().Where(n => n.Color == ConsoleColor.Red).ToList();
This works, however everytime we want to get some colored animal we would get the same type of code. We would probably write some static methods to avoid this :
List<Dog> redDogList = ListUtils.GetTheDogs(animalList);
Even better is to make this static extension methods so that the functionality looks to be encapsulated by the list its self. We can then also make the method names more readable, for instant not “GetTheDog”, but “WhichAreDog”.
For example:
public static List<Animal> WhichAreDog(this List<Animal> animalList)
{
return animalList.OfType<Dog>().Cast<Animal>().ToList();
}
public static List<Animal> HavingColor(this List<Animal> animalList, ConsoleColor color)
{
return animalList.Where(n => n.Color == color).ToList();
}
The “this” before the first parameter of the method indicates that this is an extension method on this parameter, in this case the list with animals.
Now getting the red dogs looks like this:
List<Animal> allRedDogs =
animalList.WhichAreDog().HavingColor(ConsoleColor.Red);
Much more readable and fluent!
Use an image as your UIBarButtonItem
Using an image as your UIBarButtonItem in your navigationcontroller bar can only be achieved by using a common UIButton as the BarButtonItem...
-
In ASP.NET it is easy to set the prefered authentication method in the web.config file. For external websites this is set mostly to Forms ...
-
Using an image as your UIBarButtonItem in your navigationcontroller bar can only be achieved by using a common UIButton as the BarButtonItem...
-
How to get, for example, all the hyperlinks from a webpage, which is loaded in your iPhone app using the UIWebView control? (Xcode's web...