Archive for the 'cocoa touch snippet' Category

21 JanBackground asynchronous downloads or other jobs

In current development I need to synchronize tons of data with a server. The big “Synchronize” button in the settings or somewhere else isn’t a good solution, because user starts the application to use, but wait any system jobs. So the background synchronization is more better. I found the easiest way to do it and want to share a code snippet with you.


Run method in backgorund right from UIApplicationDelegate:

- (void) startBackgroundSynch{ NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
BackgroundSynch *synch = [[[BackgroundSynch alloc] init] autorelease]; [synch startDownloading];
 [pool release];} - (void)applicationDidFinishLaunching:(UIApplication *)application 
{ [self performSelectorInBackground:@selector(startBackgroundSynch) withObject:nil];
 // Override point for customization after app launch
    [window addSubview:viewController.view];    [window makeKeyAndVisible];}

The BackgroundSynch must create NSURLConnection and receives NSURLResponse(s). But the problem you’d face with is NSURLConnection’s events (didReceiveResponse, didReceiveData, connectionDidFinishLoading) are never called. And that’s a small trick.

@interface BackgroundSynch : NSObject{ NSMutableData *responseData; BOOL finished;}
 - (void) startDownloading;@end
#import "BackgroundSynch.h" @implementation BackgroundSynch 
- (void) startDownloadingWithUrl:(NSString*)urlString{ NSLog(urlString); NSURL *url
= [NSURL URLWithString:urlString]; NSMutableURLRequest *request =  [NSMutableURLRequest
requestWithURL:url                cachePolicy:NSURLRequestReturnCacheDataElseLoad
timeoutInterval:30.0][request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]} -
(void) startDownloading{ [UIApplication sharedApplication].networkActivityIndicatorVisible =
 YES; NSString *urlString = @"http://www.archive.org/download/BettyBoopCartoons/Betty_Boop_More_
Pep_1936_512kb.mp4"; [self startDownloadingWithUrl:urlString]// THAT'S A TRICK >> finished =
 NO; while(!finished) {  [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:
[NSDate distantFuture]]; }} ////// RECEIVING DATE FROM SERVER/// - (void) connection:(NSURLConnection
 *)connection didReceiveResponse:(NSURLResponse *)response{ responseData = [[NSMutableData alloc] init];}
 - (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)aData{ [responseData
appendData:aData]; NSLog(@"DATA: %d", [responseData length]);} - (void) connectionDidFinishLoading:
 (NSURLConnection*) connection { [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
 [responseData release], responseData = nil; finished = YES;} -(void) connection:(NSURLConnection *)
connection didFailWithError:(NSError *)error { [responseData release], responseData = nil;
 [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; finished = YES;} @end

Hope you were careful enough to find an while-loop depending at the end of “startDownloading”. It depends on boolean variable which tells if data is downloading or downloaded(failed).

Now user can normally work in GUI and data automatically synchronizes on background.

11 DecUsername and Password UITextFields in UIAlertView prompt

Today I will show how to transform an UIAlertView to a prompt of username and password textfields. Actually it’s quite easy for expert of adding subviews or creating own custom controls. So current code snippet is destined for begginers.

I propose to do it in next succession:

  1. Initilize standard UIAlertView. There is a trick here. We need to set a message body to @”nnn”, it makes a shift and create a place for the text fields.
  2. Create two UITextField and initialize them with specific frames. Then add them as subviews to the UIAlertView. Don’t forget to customize a background color, placeholders, securityText property. 
  3. Lastly show UIAlertView with a little shift to top and set first UITextField as a FirstResponder if necessary.
The source code:

UITextField *textField; UITextField *textField2;

 UIAlertView *prompt = [[UIAlertView alloc] initWithTitle:@"Username and password"               message:@"nnn" // IMPORTANT             delegate:nil              cancelButtonTitle:@"Cancel"              otherButtonTitles:@"Enter", nil];

 textField = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 50.0, 260.0, 25.0)];  [textField setBackgroundColor:[UIColor whiteColor]]; [textField setPlaceholder:@"username"]; [prompt addSubview:textField];

 textField2 = [[UITextField alloc] initWithFrame:CGRectMake(12.0, 85.0, 260.0, 25.0)];  [textField2 setBackgroundColor:[UIColor whiteColor]]; [textField2 setPlaceholder:@"password"]; [textField2 setSecureTextEntry:YES]; [prompt addSubview:textField2];

 // set place [prompt setTransform:CGAffineTransformMakeTranslation(0.0, 110.0)]; [prompt show];    [prompt release];

 // set cursor and show keyboard [textField becomeFirstResponder];

11 DecThe shortest way to play sound effect on iPhone [code snippet]

  1. Define static SystemSoundID for sound effect
  2. Initilize this SystemSoundID
  3. Call our static method which plays sound effect: AudioServicesPlaySystemSound
static SystemSoundID soundFileObjectClick;
- (void)applicationDidFinishLaunching:(UIApplication *)application {
 CFURLRef soundFileURLRefClick  = CFBundleCopyResourceURL (CFBundleGetMainBundle (), CFSTR ("button-30"), CFSTR ("wav"), NULL);
 AudioServicesCreateSystemSoundID (soundFileURLRefClick, &soundFileObjectClick);
}
+ (void) clickSoundEffect{
 AudioServicesPlaySystemSound (soundFileObjectClick);
}

Please learn:

07 DeciPhone silent mode detection

Updating friend’s meditation utility there was a necessary to alert user if his device in silent mode. Silent mode is vibration on.

That’s a short snippet:

#import "AudioToolbox/AudioToolbox.h"

- (void) ifSilentModeThenMessage{ CFStringRef state; UInt32 propertySize = sizeof(CFStringRef); AudioSessionInitialize(NULL, NULL, NULL, NULL); AudioSessionGetProperty(kAudioSessionProperty_AudioRoute, &propertySize, &state);

 if(CFStringGetLength(state) == 0) {   UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Silent mode"               message:@"Please turn sound on"                delegate:self cancelButtonTitle:@"Ok"              otherButtonTitles:nil];  [alert show];  [alert release]; }}

26 NovAttaching an image of UIView to email

Today I was working on GPS Speedometer and was need to attach an UIImage of MKMapview. As it has turned out it’s very easy:

- (IBAction) email{ // CREATING MAIL VIEW MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init]; controller.mailComposeDelegate = self; [controller setSubject:@"Check this route out"]; [controller setMessageBody:@"Attaching a shot of covered route." isHTML:NO];

 // MAKING A SCREENSHOT UIGraphicsBeginImageContext(_mapView.frame.size); [_mapView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *screenshot = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();

 // ATTACHING A SCREENSHOT NSData *myData = UIImagePNGRepresentation(screenshot); [controller addAttachmentData:myData mimeType:@"image/png" fileName:@"route"]; 

 // SHOWING MAIL VIEW [self presentModalViewController:controller animated:YES]; [controller release];}

That’s how it looks:

13 NovUIView Jump Animation code snippet

I was need to make a jumping fruits in our Road Slot game for iPhone. Now have a minute to share an animation code snippet with you, guys.

Add QuartzCore framework to the project to use animation.

#define CONST_TIME_flying 0.8f

- (void) jumpAnimationForView:(UIView*)animatedView
toPoint:(CGPoint)point { // moving CGContextRef context =
 UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context];
 [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
 [UIView setAnimationDuration:CONST_TIME_flying];
 [animatedView setCenter:point];

 // scaling CABasicAnimation *scalingAnimation =
(CABasicAnimation *)
[animatedView.layer animationForKey:@"scaling"];
if (!scalingAnimation)
 {  scalingAnimation =
[CABasicAnimation animationWithKeyPath:@"transform"];
 scalingAnimation.duration=CONST_TIME_flying/2.0f;
 scalingAnimation.autoreverses=YES;
 scalingAnimation.timingFunction =
[CAMediaTimingFunction functionWithName:
kCAMediaTimingFunctionEaseOut];
scalingAnimation.fromValue=[NSValue valueWithCATransform3D:
CATransform3DMakeScale(1.0, 1.0, 1.0)];
 scalingAnimation.toValue=[NSValue valueWithCATransform3D:
CATransform3DMakeScale(1.4, 1.4, 1.0)]; }
 [animatedView.layer addAnimation:scalingAnimation forKey:@"scaling"];
[UIView commitAnimations];}

- (IBAction) buttonPressed :( UIButton*)button{
[self jumpAnimationForView:button toPoint:
(CGPoint){rand()%320, rand()%480}];}

The UIButton simply jumps to random point on its

UIView each time you press it. That’s how it looks:

07 NovSource snippets from Alarm like iPhone application

Today I made a very simple alarm like application. It’s my friend’s request.

He wanted a mobile app that can ONLY time a certain period.

In contrast to built-in iPhone Timer it must NOT to show how much time past from begin and simply plays random song from the iPod when the time is up. Unusually? Agreed. Nothing must distract friends’ minds while meditations ;)

While coding this helpful utility I used several new APIs of iPhone SDK 3.0 (3.1.2). Catch some source snippets.

So my friend wants to hear nothing while meditation and to be waked up by a random song from iPod library. Do mute playing music at the start:

if ([[MPMusicPlayerController iPodMusicPlayer] playbackState]
== MPMusicPlaybackStatePlaying)  [[MPMusicPlayerController iPodMusicPlayer] pause];

make a vibration and keep playing at the end:

AudioServicesPlaySystemSound(kSystemSoundID_Vibrate)if ([[MPMusicPlayerController iPodMusicPlayer] playbackState]
== MPMusicPlaybackStateStopped) {  [[MPMusicPlayerController
iPodMusicPlayer] setShuffleMode:MPMusicShuffleModeSongs];
 [[MPMusicPlayerController iPodMusicPlayer]
 setQueueWithQuery: [MPMediaQuery songsQuery]];
}  [[MPMusicPlayerController iPodMusicPlayer] play];

To increase iPhone battery life we must turn on the proximity sensor which

monitors if there is something very close and make a screen dim if necessary.

Put your device downscreen and it dims. iPhone autolocking must be turn off.

[[UIApplication sharedApplication] setIdleTimerDisabled:YES];
/ / disable autolocking [[UIDevice currentDevice]
setProximityMonitoringEnabled:YES];  // enable screen dimming

remember input value:

static BOOL idleTimerDisabled;
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
- (void)applicationDidFinishLaunching:(UIApplication *)application
 { idleTimerDisabled =
 [[UIApplication sharedApplication] isIdleTimerDisabled]; ...}

turn off the proximity sensor and set input autolocking setting on application exit (including home-button exit):

- (void)applicationWillTerminate:(UIApplication *)application{ [[UIDevice currentDevice]
setProximityMonitoringEnabled:NO]; [[UIApplication sharedApplication] setIdleTimerDisabled:
idleTimerDisabled]; // disable autolocking}

I will make a special post when this Vipassana meditation utility will be available on app store.