How change string to URL format (percent escapes)

iPhone cocos2d Tips & Tricks

NSString *myString = @"just sample";
myString = [myString stringByAddingPercentEscapesUsingEncoding: NSASCIIStringEncoding];
NSLog(@"%@", myString); //output: just%20sample

CerBer (Petualangan Tukang Roti ~ Part1)

Berhubung KucingLorenk n KucingItem lagi bosen... kami memutuskan buat bikin cerita bersambung... masing2 nulis 1 kalimat bergantian.... tema yang di pilih adalah MISTERI... ini hasil nya... (judul cerita masi blom di tentukan...)

KucingLorenk = lorenk, KucingItem = item

item : Ada sebuah gubuk tua di tengah hutan lebat..... gubuk itu sungguh reok... hampir roboh....
item : *bhs indo mar makin kaco susunan nya*
lorenk : lalu datang lah penjual roti yg kesesat kesana....
item : "rotiii~~ rottii~~" teriak si penjual roti yg belum menyadari kalo dia tersesat...
item : *feeling mar.. ini bakal jd cerita komedi...*
lorenk : *emoticon ketawa*
item : jgn ketawa!
item : buruan lanjutin...
item : apa si yg ga jd ancur di kita...
lorenk : "roti bang~~" terdengar sahutan dari dalam gubuk tersebut...
item : si penjual roti terkejut mendengar suara itu... sambil menuju k gubuk tua itu.... tiba-tiba!!!
lorenk : curang apaan noh
item : *kok ga keren bgt si??? masa tokoh utama nya penjual roti!!!*
item : emang curang...
lorenk : jgn menghina tukang roti donk
item : iya de..
item : lanjuttt
lorenk : hmm...
lorenk : tukang roti itu sebenarnya takut, tapi karena lagi butuh uang dia memberanikan diri... sampai di sana dia melihat tidak ada siapa pun diluar...
item : "roti bang~" suara itu kembali terdengar dari salah satu kamar di gubuk itu...
lorenk : "mau beli roti apa?" balasnya dari luar.. ga berani masuk dia.
item : *kok tata bhs nya uda berubah??*
lorenk : jgn cerewet
item : tidak terdengar sautan dari dalam gubuk.... sekelebat terlihat bayangan putih melintas dari salah satu jendela di gubuk itu...
lorenk : O_O seremm...
item : oi!
item : kan cerita misteri
lorenk : *dan 1 narator kabur
item : *OIIIIIII
item : tangkep
lorenk : unu
item : lanjuttt
item : ntar mar copas neh cerita nya ah.. bikin blog...
lorenk : dengan sedikit rasa takut penjual roti itu membuka pintu depan.. krieet.."rotinya jadi tidak?"
lorenk : heeee
lorenk : ga deh
item : ayo laaaaa... ya ya ya ya?
lorenk : penjual roti ga ada nilai jual
lorenk : lanjut sana
item : umm... td sapa yg bilang.... jgn remehkan penjual roti...
lorenk : ...
item : penjual roti terkejut melihat keadaan gubuk itu... penuh debu dan gelap seperti rumah yang udah lama tak di huni.... "roti bang~" suara itu terdengar lagi...
lorenk : *nih tukang roti mana, deliverynya mantap ampe masuk2 ke rmh
item : *iya... berani mati pula neh tkg roti*
lorenk : "terdengarnya dari lantai atas, ah mungkin dia sudah kelaparan sekali, sampai tidak kuat turun, baik akan saya samperin dia" pikir tukang roti..
item : "permisi~
item : aduh kepencet
item : "permisi~" kata tukang roti.. perlahan2 tukang roti berjalan menuju tangga... *terlihat di latar belakang, pintu gubuk ketutup sendiri*
lorenk : menyadarinya, tukang roti balik dan mencoba membuka pintu itu kembali, "waduh terkunci, saya jgn diapa2in donk..." jeritnya....
lorenk : ga bisa bikin cerita misteri aaah
item : WEEEEEEEEEE
item : CERITA MISTERI OIIIIIIII
lorenk : ya dah lanjut gih
item : di tolak
item : apa2an tuh
lorenk : unu??
lorenk : ok ganti deh..
lorenk : "ah angin bikin pintunya nutup sendiri, bikin kaget aja" kata penjual roti sambil naik tangga, namun dia merasakan bahwa tangga itu basah...
item : "ah.. kok basah ya pegangan tangga nya..." tukang roti melihat telapak tangan nya... yang basah oleh darah....
item : *mule serius neh cerita nya!*
lorenk : *serem mar.. is mengundurkan diri @_@
item : weh!
lorenk : "lho kok ada darah, apa ada yang terluka disini?" kagetnya, "permisi, anda dimana? apa anda baik2 saja?" tanya penjual roti...
item : tiba2 lampu di dalam gubuk kedip2 lalu mati! gubuk menjadi gelap... hening tanpa suara...
lorenk : penjual roti itu menjadi ketakutan.. dengan gemetar dia berusaha menyalakan korek api yg dia bawa..... alangkah terkejutnya dia dengan apa yg diliatnya!!!
lorenk : tukang roti kdg2 merokok jg kan
item : tapak tangan berdarah di lantai dan di dinding gubuk!! terkejut, tanpa sengaja tukang roti menjatuhkan korek api nya... gubuk kembali menjadi gelap...
lorenk : ....
lorenk : berhubung uda mau pulang....
lorenk : to be continue...

Tween doesn't finish sometimes

Flash Tips and Tricks

If you have problem with not finishing tween in flash AS3, this is how to fix it:
var tweensArray :Array = [];
var myTween:Tween = new Tween(movieClip, , "alpha", None.easeOut, 0, 1, 2, true);
tweensArray.push(myTween);

Set Accelerometer interval

iPhone SDK Tips & Tricks

[[UIAccelerometer sharedAccelerometer] setUpdateInterval:(1.0 / 30)];

Sprite Anchor

iPhone cocos2d Tips & Tricks

[sprite setTransformAnchor:ccp(0,0)]; //lower left
or
[sprite setAnchorPoint:ccp(0,0)]

scene transition

iPhone cocos2d Tips & Tricks

[[Director sharedDirector] replaceScene:[RotoZoomTransition transitionWithDuration:1.0 scene:scene]];



see: cocos2d/Transition.h

fix gradient

iPhone cocos2d Tips & Tricks

[[Director sharedDirector] setPixelFormat:kRGBA8];

add and run scene object

iPhone cocos2d Tips & Tricks

[[Director sharedDirector] runWithScene:scene];

attach the window to cocos2d director

iPhone cocos2d Tips & Tricks

[[Director sharedDirector] attachInWindow:window];

Landscape view

iPhone cocos2d Tips & Tricks

[[Director sharedDirector] setDeviceOrientation:CCDeviceOrientationLandscapeLeft];

or

[[Director sharedDirector] setLandscape: YES];

or

[application setStatusBarOrientation: UIInterfaceOrientationLandscapeRight animated:NO];

Get device name and model

iPhone SDK Tips & Tricks

NSString *nameString = [UIDevice currentDevice].name;
NSString *typeString = [UIDevice currentDevice].model;
NSString *infoStrings = [NSString stringWithFormat: @"Device Name: %@, Device Type: %@", nameString, typeString];

Increase default.png's time on screen

iPhone SDK Tips & Tricks

go into your app delegate's implementation file (.m) and right underneath the following code:

- (void)applicationDidFinishLaunching:(UIApplication *)application
{
sleep(x);
...
}


"x" is the number of seconds you want to display the default screen for.

Or:

[NSThread sleepForTimeInterval:1.0];

Check internet connection is available

iPhone SDK Tips & Tricks

Add the SystemConfiguration framework - also don't forget to

#import "SystemConfiguration/SCNetworkReachability.h"
#include "netinet/in.h"

- (BOOL) connectedToNetwork
{
// Create zero addy
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;

// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;

BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);

if (!didRetrieveFlags)
{
printf("Error. Could not recover network reachability flags\n");
return 0;
}

BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
return (isReachable && !needsConnection) ? YES : NO;
}

Background text at empty textfield

iPhone SDK Tips & Tricks

We use placeholder to fill the UITextField with a background text until it is touched and/or has any input.
myTextfield.placeholder = @"First Name...";

Password textfield

iPhone SDK Tips & Tricks

To have the text field show asterisks, add this line when you create the text field (or wherever)
yourTextField.secureTextEntry = YES;

Remove space and new line (\n) in string

iPhone SDK Tips & Tricks

myString = [myString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

whitespaceCharacterSet → only remove space

Resize Multi-line Text to Fit UILabel on iPhone

iPhone SDK Tips & Tricks


//Create a string with the text we want to display.
self.ourText = @"This is your variable-length string. Assign it any way you want!";

/* This is where we define the ideal font that the Label wants to use.
Use the font you want to use and the largest font size you want to use. */
UIFont *font = [UIFont fontWithName:@"Marker Felt" size:28];

int i;
/* Time to calculate the needed font size. This for loop starts at the largest font size, and decreases by two point sizes (i=i-2) Until it either hits a size that will fit or hits the minimum size we want to allow (i > 10) */
for(i = 28; i > 10; i=i-2)
{
// Set the new font size.
font = [font fontWithSize:i];
// You can log the size you're trying: NSLog(@"Trying size: %u", i);

/* This step is important: We make a constraint box
using only the fixed WIDTH of the UILabel. The height will
be checked later. */
CGSize constraintSize = CGSizeMake(260.0f, MAXFLOAT);

// This step checks how tall the label would be with the desired font.
CGSize labelSize = [self.ourText sizeWithFont:font constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];

/* Here is where you use the height requirement!
Set the value in the if statement to the height of your UILabel
If the label fits into your required height, it will break the loop
and use that font size. */
if(labelSize.height <= 180.0f)
break;
}
// You can see what size the function is using by outputting: NSLog(@"Best size is: %u", i);

// Set the UILabel's font to the newly adjusted font.
msg.font = font;

// Put the text into the UILabel outlet variable.
msg.text = self.ourText;


Add shadow to label's text

iPhone SDK Tips & Tricks

myLabel.shadowColor = [UIColor darkGrayColor];
myLabel.shadowOffset = CGSizeMake(1.0,1.0);


The shadowOffset controls set how far on the x- and y-axes from the label's text the shadow is drawn. The default is {0,-1}.

Creating an UIImage from a URL/server

iPhone SDK Tips & Tricks

NSString *path = @"http://merrimusings.mu.nu/archives/images/groundhog2.jpg";
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data cache:NO];

Change app file name

iPhone SDK Tips & Tricks

Targets -> -> right click, info
choose build tag -> packaging heading -> product name

remove glossy effect from app Icon

iPhone SDK Tips & Tricks

In info.plist, add row:
(right click, show raw keys/values)
UIPrerenderedIcon -> set value YES

Keyboard handling

iPhone SDK Tips & Tricks


Keyboard Show:
[searchBar becomeFirstResponder];


Keyboard hide:
[searchBar resignFirstResponder];

check collision

iPhone SDK Tips & Tricks

if(CGRectIntersectsRect(circle1.frame, circle2.frame)
{
NSLog(@”touched”);
}

Hide status bar

iPhone SDK Tips & Tricks

At info.plist:
status bar is intially hidden -> set value YES

or. programmatically,

[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];

Replace string

iPhone SDK Tips & Tricks


NSMutableString *myString = [[NSMutableString alloc] initWithString:@”this and that”];
[
myString replaceOccurencesOfString:@”this” withString:@”that” options:NSCaseInSensitiveSearch range:NSMakeRange(0, [myString length])];
NSLog(@"%@",
myString);

or
myString = [myString stringByReplacingOccurrencesOfString:@"this"
withString:@"that
"];

auto-lock disable

iPhone SDK Tips & Tricks

[[UIApplication sharedApplication] setIdleTimerDisabled:YES];

Set badge

iPhone SDK Tips & Tricks

[[UIApplication sharedApplication] setApplicationIconBadgeNumber:2];
or
[UIApplication sharedApplication].applicationIconBadgeNumber = 2;

remove badge => set 0

Scroll textview to first line

iPhone SDK Tips & Tricks

[myTextView scrollRangeToVisible:NSMakeRange(0,1)];

Alert with textfield

iPhone SDK Tips & Tricks

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Login" message:@"username\npassword\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];

usernameTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 40.0, 260.0, 25.0)];
[usernameTextField setBackgroundColor: [UIColor whiteColor]];
usernameTextField.placeholder = @"Username";
[usernameTextField becomeFirstResponder];
[alert addSubview:usernameTextField];

passwordTextField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 70.0, 260.0, 25.0)];
passwordTextField.placeholder = @"Password";
[passwordTextField setBackgroundColor: [UIColor whiteColor]];
[alert addSubview:passwordTextField];

Alert

iPhone SDK Tips & Tricks

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Title” message:@”An alert” delegate:self cancelButtonTitle:@”No” otherButtonTitles:@”Yes”, nil];

Display float dan integer

iPhone SDK Tips & Tricks


%8d => 12345 -> 00012345
%.2f
%10.2f

int x = 123456;
%2d => 123456
%4d => 123456
%6d => 123456
%8d => 123456

Handling Interruptions (call)

iPhone SDK Tips & Tricks

-(void)applicationWillResignActive:(UIApplication *)application
{
//code here
}

Text bounds

iPhone SDK Tips & Tricks

myLabel.text = newText;
CGRect bounds = myLabel.bounds;
bounds.size = [newText sizeWithFont:myLabel.font];
myLabel.bounds = bounds;

Make subviews visible outside the boundaries of their superviews

iPhone SDK Tips & Tricks

myView.clipsToBounds = NO;

Convert float to int

iPhone SDK Tips & Tricks


int myInteger = (int)(myFloat * 3.280839895 + 0.5);

float -> 23.0000
int -> 23

Convert string to integer, float, double

iPhone SDK Tips & Tricks

NSString *intString =@"1";
int value = [intString intValue]; //1

floatValue -> 1.00
doubleValue ->1.0000000

Random

iPhone SDK Tips & Tricks

int lastNumber;
int rNumber;
while(rNumber == lastNumber)
rNumber = arc4random()%10;
lastNumber = rNumber;

Send email

iPhone SDK Tips & Tricks

[UIApplication sharedApplication] openURL:[NSURK URLWithString:@”mailto:someone@email.com?subject=subject%20sample&body=body”]];

for iPhone OS 3:
Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
if([mailClass canSendMail])
{
MFMailComposeViewController *mailCompose = [[[MFMailComposeViewController alloc] init] autorelease];
mailCompose.mailComposeDelegate = self;
[mailCompose setToRecipients:[NSArray arrayWithObject:@"x@yahoo.com", @"y@yahoo.com"]];
[mailCompose setSubject:@"subject sample"];

//attachment
UIImage *myImage = [UIImage imageNamed:@"box.png"];
NSData *imageData = UIImageJPEGRepresentation(
myImage, 1);
[mailCompose addAttachmentData:imageData mimeType:@"image/png" fileName:@"box.png"];

[mailCompose setMessageBody:messageBody isHTML:YES];
[self presentModalViewController:mailCompose animated:YES];
}

Open browser

iPhone SDK Tips & Tricks

[UIApplication sharedApplication] openURL:[NSURL URLWithString:@”http://www.google.com”]];

Compare Date & String

iPhone SDK Tips & Tricks

NSDateComponents *compsDisplay = [[NSDateComponents alloc] init];
[compsDisplay setDay:1];
[compsDisplay setMonth:9];
[compsDisplay setYear:2009];
NSCalendar *gregorianDisplay = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDate *dateDisplay = [gregorianDisplay dateFromComponents:compsDisplay];
NSDate *now = [NSDate date]; //today date

if([dateDisplay compare:now] == NSOrderedDescending)
{
NSLog(@”date display is bigger that now”);
}

NSComparisonResult:

NSOrderedAscending
NSOrderedDescending
NSOrderedSame

Save and Read Data

iPhone SDK Tips & Tricks

Save data:
NSString *testValue = [[NSUserDefaults standartUserDefaults] stringForKey:@”stringKey”];
if(testValue == nil)
{
//set default value
[[NSUserDefaults standartUserDefaults] setInteger:42 forKey:@”intKey”];
[[NSUserDefaults standartUserDefaults] setObject:@”data” forKey:@”stringKey”];
[[NSUserDefaults standartUserDefaults] setDouble:3.1415 forKey:@”doubleKey”];
[[NSUserDefaults standartUserDefaults] setFloat:1.23 forKey:@”floatKey”];

[[NSUserDefaults standartUserDefaults] synchronize];
}


Read data:
NSString *defaultString = [[NSUserDefaults standartUserDefaults] stringForKey:@”stringKey”];
int defaultInt = [[NSUserDefaults standartUserDefaults] integerForKey:@”intKey”];
//or NSInteger *defaultInt
int defaultFloat = [[NSUserDefaults standartUserDefaults] floatForKey:@”floatKey”];

Split string to array

iPhone SDK Tips & Tricks

NSString *fileContents = @”mu sample string...”
NSArray *phraseArray = [fileContents componentsSeparatedByString:@”\n”];

NSLog(@”%@”, [phraseArray objectAtIndex:0]);

Read File

iPhone SDK Tips & Tricks

NSString *nameFile = [NSString stringWithFormat:@”data”];
NSString *phrasesFile = [[NSBundle mainBundle] pathForResource:nameFile ofType:@”txt”];
NSString *fileContents = [NSString stringWithContentsOfFile:phrasesFile encoding:NSUTF8StringEncoding error:nil];

Change button style

iPhone SDK Tips & Tricks

myButton.barStyle = UIBarStyleBlackTranslucent;

UIBarStyle:
UIBarStyleBlackTranslucent - gray
UIBarStyleDefault - blue
UIBarStyleBlackOpaque - black

Show date

iPhone SDK Tips & Tricks


NSDate *now = [NSDate date]; //today date
NSLog(@"%d", [[now dateWithCalendarFormat:nil timezone:nil dayOfMonth]);


NSCalendarDate Class Reference:
dayOfMonth
dayOfWeek
monthOfYear
yearOfCommonEra
hourOfDay
minuteOfHour
secondOfMinute

Create animation

iPhone SDK Tips & Tricks

Image is getting smaller and missing:
- (void)throwaway
{
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5]; //in seconds
myImageView.transform = CGAffineTransformMakeScale(.001, .001);
[UIView commitAnimations];
}


To return to normal size:
myImageView.transform = CGAffineTransformIdentity;

Drag Image

iPhone SDK Tips & Tricks


- (void)loadView
{
UIImageView *paperView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
paperView.image = [UIIamge imageNamed:@”paper.png”];
paperView.userInteractionEnabled = YES;

}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
UITouch *touch = [touches anyObject];

if([touch view] == paperView)
{
paperView.center = [touch locationInView:self];
}
}


Absolute Value

iPhone SDK Tips & Tricks

float floatValue = -123.45678;
NSLog(@"%f", fabsf(floatValue)); //output: 123.45678