Skip to content
Apr 21 12

Passing Data with TTNavigator

by dkberktas

Three20 has a nice way of handling navigation between controllers. One thing that is not immediately obvious is passing data to the controller. From the sample code and the extremely short wiki page, we can see how to pass data with a query parameter when there is another parameter.

NSArray*arr =[...load up with data...];
[[TTNavigator navigator] openURLAction:[[TTURLAction actionWithURLPath:@"tt://restaurant/Chotchkie's"]
applyQuery:[NSDictionary dictionaryWithObject:arr forKey:@"arrayData"]]];
-(id) initWithName:(NSString*)name query:(NSDictionary*)query 
{
  for(MyObject* item in[query objectForKey:@"arrayData"])
  //... do something with item ...
}

// ...

}

But, what happens when you only want to pass the query parameter?

 - (id)initWithNavigatorURL:(NSURL*)URL query:(NSDictionary*)query

Obvious right!

Thanks StackOverflow

Jan 26 12

iOS and Custom Fonts

by dkberktas


Recently, I was working on a game with Cocos2d and keep getting this weird iOS version problem. On iOS 5, all my labels were shown as expected but on iOS 4 labels somehow kept disappearing. First I thought this is because of the retina display and point/pixels stuff. However, it was because of the fonts I was using. HelveticaNeue-CondensedBold and HelveticaNeue-CondensedBlack are available on iOS 5, but not on iOS 4 (http://iosfonts.com/).

I googled to see how easy to add custom fonts and it turned out, it is super easy.

These are the links I found helpful:

  • Adding custom fonts by Dave Allanson (link)
  • Using Custom Fonts by M. Arsalan Anwar (link)
Steps to Add Custom Font:
1. Add font files to project
2. Open your Info.plist file
3. Create the key “UIAppFonts”  as Array (it will be shown as “Fonts provided by application”  if you are not on Ras Key/Value state, right click and you will see what I mean)
4. Add the fonts to the array
5. In your code, you can use these fonts as if you are using the regular ones (without the file extension).
Drawing Problems:
If you get the fonts from Adobe, we will get a drawing problem like mentioned here. You need to follow the steps here, change the font file’s ascender property. Don’t worry it is not that scary as it seems ;) Don’t forget to install Apple Font Tool Suite from here.
Feb 21 11

Animating Views with iPhone Keyboard

by dkberktas

Keyboards on iPhone can be a headache with their half screen size, especially when you have many input fields on a single view. Animating the view in an elegant way so that the input fields are always visible to the user  requires to slide up or down with the keyboard synchronously.

Following is a very simple view based project, that will demonstrate animating view with keyboard slide up/down.
But first, let’s see the problem. If you don’t change your view positioning when the keyboard becomes visible, basically you are likely to get something like this:

To fix that, what should be done is to listen the keyboard slide up/down notifications through the NSNotificationCenter, which viewWillAppear is a good place to start listening these two notifications.

-(void)viewWillAppear:(BOOL)animated
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(slideUpView:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(slideDownView:) name:UIKeyboardWillHideNotification object:nil];
}

Second step is to change the positioning of the components according to the animation of the keyboard. The following methods are called when there is a notification from the keyboard:

-(void)slideDownView:(NSNotification*)notification
{
	[[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&keyboardFrame];

	[UIView animateWithDuration:animationDuration
				delay:0.0
				options:animationCurve
				animations:^{
					self.view.frame = CGRectMake(0, 0, 320, 480);
				}
				completion:^(BOOL finished){
					NSLog(@"Slide down Done..!");
				}];
}

-(void)slideUpView:(NSNotification*)notification
{
    [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&animationCurve];
    [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&keyboardFrame];
	//
	[UIView animateWithDuration:animationDuration
				delay:0.0
				options:animationCurve
				animations:^{
					self.view.frame = CGRectMake(0, -keyboardFrame.size.height + 70, 320, 416);
				}
				completion:^(BOOL finished){
					NSLog(@"Slide up Done..!");
				}];
}

Don’t forget to add .h file the following declarations:

// in controller's .h file
NSTimeInterval animationDuration;
UIViewAnimationCurve animationCurve;
CGRect keyboardFrame;

The final result is something like this

note 1: Feel free to download the source code (link). It also includes the slide down via the button.
note 2: The licence to this peace of code is Beerware, In short, “Should the user of the product meet the author and consider the software useful, he is encouraged to buy the author a beer ‘in return’ (or, in some variations, drink a beer in the author’s honor).”

Nov 23 10

Signing Up to AWS and Creating your First EC2 Instance — A Step by Step Guide

by dkberktas

There are lots of sources about  how to start AWS EC2, but this abundance can be intimidating and confusing. During the last summer, when I tried to find a hosting solution for Remotespots, I briefly tried AWS EC2, but then switched to Eapps since they speed things up.

What you need to do in three steps is that

  • Sign up to AWS, connect to AWS (preferable with Amazon EC2 API Tools)
  • Create an instance (via API tools or the web console)
  • Connect to that instance via SSH.

These are the steps that works for me,

1. Sign up AWS — http://aws.amazon.com/

2. Follow the steps at that link, and create X.509 certificate (also download private key when doing that)

3. Create an instance from the https://console.aws.amazon.com/ec2/ (Don’t forget to save the private key .pem file while creating the instance)

5. Follow the steps here http://paulstamatiou.com/how-to-getting-started-with-amazon-ec2 for connecting to the instance via SSH.

Links that helps :)

- AWS console – https://console.aws.amazon.com/ec2/

- AWS portal — https://aws-portal.amazon.com/

- Starting Amazon EC2 with Mac OS X — http://www.robertsosinski.com/2008/01/26/starting-amazon-ec2-with-mac-os-x/

- How To: Getting Started with Amazon EC2 — http://paulstamatiou.com/how-to-getting-started-with-amazon-ec2

- Connect to Your Linux/UNIX Instance — http://docs.amazonwebservices.com/AWSEC2/latest/GettingStartedGuide/

Nov 22 10

Saving UIImage as a PNG with an Alpha Channel (with transparency) on iOS

by dkberktas

Say you let your user draw thing and let them go wild with their imaginations, as they probably create awesome drawings, you should probably want to save these images to somewhere.

After this short happy talk, here is the code snippet that saves your UIImage to the Documents folder with its alpha channel, if there is one. The other method is for reading that image back to an UIImage instance.

-(void)saveImageToDocs:(NSString *)fileName
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *filePath2 = [NSString stringWithFormat:@"%@/%@.png", documentsDirectory, fileName];

	// If you use this method, the transparency will be lost
	//NSData* imageData = UIImageJPEGRepresentation(drawImage.image, 1.0);
	//NSData* imageData = UIImagePNGRepresentation(drawImage.image);
	//[imageData writeToFile:filePath2 atomically:NO];

	// So use this one
	[UIImagePNGRepresentation(myUIImage) writeToFile:filePath2 atomically:YES];
}

-(void)loadImageFromDocs:(NSString *)fileName
{
	NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
	NSString *filePath2 = [NSString stringWithFormat:@"%@/%@.png", documentsDirectory, fileName];
	if([[NSFileManager defaultManager] fileExistsAtPath:filePath2])
	{
		NSLog(@"image file exists");
		myUIImage = [UIImage imageWithContentsOfFile: filePath2];
	}
}
Nov 10 10

E-ticaret Kitabindan Notlar

by dkberktas

Normalde e-ticaret’te soyle yapmali, basariya giden yol icin oneriler vs kitaplari pek samimi olmuyor gibi, bu kitaba da uykumu getirmesi icin soyle bir bakayim diye elime aldim, ama icinde etohum projeleri ile ilgili yazilar gorunce okumaya karar verdim.

Digital Age dergisnin Kasim 2010 sayisi ile verilen “e-ticaret Satista Tsunami Etkisi — Anil Altas” kitabi (Sina Afra’nin onsozunu yazmis) hafif uzun bir blog yazisi gibi okunabiliyor. Iki saat gibi bir surede bitirebilirsiniz.

Kitabi okurken aldigim notlar ve ilgimi ceken maddeler asagidaki gibi:

“Would you tell me, please, which way I ought to go from here?”
“That depends a good deal on where you want to get to,” said the Cat.
“I don’t much care where–” said Alice.
“Then it doesn’t matter which way you go,” said the Cat.
“–so long as I get SOMEWHERE,” Alice added as an explanation.
“Oh, you’re sure to do that,” said the Cat, “if you only walk long enough.”
(Alice’s Adventures in Wonderland, Chapter 6)

(http://www.alice-in-wonderland.net/books/alice-in-wonderland-quotes.html)

Oct 16 10

Data Storage Alternatives on iOS (in a Nutshell)

by dkberktas

Below you can find the summary of available alternatives for storing data on iOS based machines. Mainly, which one to use depends on your needs like size of data, need of concurrency, access speed, etc.

  • NSUserDefaults
    • Based on plists
    • Store lightweight app state
    • Tutorial (link)
  • Plist — Writing everything out as a plist
    • Not suitable for complex model objects
    • Faster than NSUserDefaults
    • How to load a plist (link)
    • Write & Read data to .plist (link)
  • Archived Objects
    • Conteptual guide (link)
    • Archives provide a means to convert objects and values into an architecture-independent stream of bytes that preserves the identity of and the relationships between the objects and values.
    • Serialization converts Objective-C types to and from an architecture-independent byte stream. In contrast to archiving, basic serialization does not record the data type of the values nor the relationships between them; only the values themselves are recorded. Arbitrary objects cannot be serialized. Only instances of NSArray, NSDictionary, NSString, NSDate, NSNumber, and NSData (and some of their subclasses) can be serialized. (link)
    • Forum post about how to use archiver (link)
  • The joy of SQLite
    • Basically a local file act like a database server
    • Not very good for extreme concurrent access
    • A step by step tutorial (link)
  • Core Data
    • Higher abstraction layer than SQLite
    • Save&load model objects
    • ORM (Rails ActiveRecord, Java Hibernate)
    • Use NSPredicate for in memory filtering
    • Apple Dev Center Article (link)
  • Web Services
    • Store & access remote data
    • XML and Json parsers

ps. Related Stackoverflow entry

Sep 14 10

Amazon S3 and Paperclip on Rails 3

by dkberktas

I previously posted about Using Amazon S3 with Paperclip. This post will talk about same topic. But this time for Rails 3.

  • Install aws-s3 by adding Gemfile
    gem 'aws-s3'

    and run

    bundle install
  • Create s3.yml file under config directory and enter your Amazon S3 credentials (also I assume you created the buckets for development and production)
    development:
      bucket: bucket-dev
      access_key_id: xxx
      secret_access_key: xxx
    test:
      bucket: bucket-test
      access_key_id: xxx
      secret_access_key: xxx
    production:
      bucket: bucket-pro
      access_key_id: xxx
      secret_access_key: xxx
  • Open your model file that will hold the attachment and modify it as follows:
      #paperclip
      has_attached_file :photo,
           :styles => {
           :thumb=> "100x100#",
           :small  => "400x400>" },
         :storage => :s3,
         :s3_credentials => "#{RAILS_ROOT}/config/s3.yml",
         :path => "/:style/:id/:filename"
  • That’s it! Simple isn’t it.

    links that might help

  • http://docs.heroku.com/s3
  • http://stackoverflow.com/questions/3055105/establishing-connection-w-amazon-s3-from-heroku
  • Sep 12 10

    Paperclip on Rails 3 — damn easy!

    by dkberktas

    Paperclip is a Rails plug-in for attaching files to models. Using Paperclip is also very easy to use, it can thumbnail your images and also send the files to Amazon S3.

    From this link, you can find the steps for creating a Rails project from scratch with paperclip.
    http://jameswilding.net/2010/07/24/paperclip-rails-3/

    As I have already had a project that needs file attachments, I follow a slightly different path.

    The steps for adding a file attachment is as follows:

    1. Install Paperclip
    2. $ rails plugin install git://github.com/thoughtbot/paperclip.git
    3. Add image attribute to your model
    4.   #paperclip
        has_attached_file :photo,
           :styles => {
             :thumb=> "100x100#",
             :small  => "400x400>" }
    5. Create migration file and add the necessary columns to your database
    6. $ rails generate migration add_photo_to_microposts photo_file_name:string photo_content_type:string photo_file_size:integer
      rake db:migrate
    7. Change you form
    8. <%= form_for @micropost  , :html => { :multipart => true } do |f| %>
      <%= f.file_field :photo %>
      ...
    9. Change view that will show the uploaded image (optional)
    10. <% if micropost.photo.exists? then %>
      	<%= image_tag micropost.photo.url(:small) %>
      <% end %>

    That’s it. It is done.

    Sep 3 10

    So How Do You Convince Google App Engine to Create Your Datastore Indexes

    by dkberktas

    Creating indexes on Google App Engine / Java (gae/j) is an easy job. You don’t even have to think about it (well, for some time)

    For etohum admin application we used gae/j and it has been almost two years and gae/j has been improved a lot, but still, it has some really annoying features (bugs — I am not sure how to named them).

    This time, it is the Datastore Indexes. Some of the pages requires indexes like

    which turns out to be confusing for the auto generation tool. If, let’s say, you change the order of the last two fields,

    like this

    you will not get it automatically.

    Even if you explicitly define it in your  datastore-indexes.xml file

    <datastore-index kind="Application" ancestor="false" source="manual">
     <property name="applciationIsFinished" direction="asc"/>
     <property name="isSpam" direction="asc"/>
     <property name="sezonId" direction="asc"/>
     <property name="bitisTarihi" direction="desc"/>
     <property name="basvuruTarihi" direction="desc"/>
     </datastore-index>
    

    And the workaround for the problem is stated in the last paragraph of Using Automatic Index Configuration documentation

    It’s a good idea to occasionally move index configuration from datastore-indexes-auto.xml to datastore-indexes.xml, then disable automatic index configuration and test your app in the development server. This makes it easy to maintain indexes without having to manage two files, and ensures that your testing will reproduce errors caused by missing index configuration.

    So change the datastore-indexes.xml file and add manually the all required indexes and upload the application.

    <datastore-indexes autoGenerate="false">

    You can change it back to auto generate after make sure the desired indexes are created.

    ps. A tip about gae/j is that it is considerable faster when it is 4AM-7AM at the west coast of North America.