{"id":2302,"date":"2011-05-23T23:03:56","date_gmt":"2011-05-23T18:03:56","guid":{"rendered":"http:\/\/aasims.wordpress.com\/?p=2302"},"modified":"2025-04-27T20:18:04","modified_gmt":"2025-04-27T20:18:04","slug":"ios-code-bites","status":"publish","type":"post","link":"https:\/\/aasimnaseem.com\/blog\/ios-code-bites\/","title":{"rendered":"iOS Code Chunks &#8211; Part 2"},"content":{"rendered":"<div>\n<p>Hello iFellows;<br \/>\nHope all are enjoying your life.<\/p>\n<p>Today, there are \u00a0some tips for new iDevelopers. These code chunks will help you out to do some really simple and many-time-usable things.<\/p>\n<p>Bring coke and have some light track in iTunes.<\/p>\n<p>So here we go;<\/p>\n<p><!--more--><\/p>\n<p><strong>Logging<\/strong><\/p>\n<\/div>\n<p>In Xcode, click Run &gt; Console to see NSLog statements.<\/p>\n<p>[sourcecode language=&#8221;objc&#8221;]<br \/>\nNSLog(@&amp;amp;quot;log: %@ &amp;amp;quot;, myString);<br \/>\n NSLog(@&amp;amp;quot;log: %f &amp;amp;quot;, myFloat);<br \/>\n NSLog(@&amp;amp;quot;log: %i &amp;amp;quot;, myInt);<br \/>\n[\/sourcecode]<\/p>\n<div>\n<p><strong>Display Images<\/strong><\/p>\n<p>Display an image anywhere on the screen, without using UI Builder. You can use this for other types of views as well.<\/p>\n<p>[sourcecode language=&#8221;objc&#8221;]<br \/>\nCGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f);<br \/>\nUIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect];<br \/>\n[myImage setImage:[UIImage imageNamed:@&amp;amp;quot;myImage.png&amp;amp;quot;]];<br \/>\nmyImage.opaque = YES; \/\/ explicitly opaque for performance<br \/>\n[self.view addSubview:myImage];<br \/>\n[myImage release];<br \/>\n[\/sourcecode]<\/p>\n<div>\n<p><strong>Application Frame<\/strong><\/p>\n<\/div>\n<p>Use &#8220;<strong>bounds<\/strong>&#8221; instead of &#8220;<strong>applicationFrame<\/strong>&#8221; &#8212; the latter will introduce a 20 pixel empty status bar (unless you want that..)<\/p>\n<div>\n<p><strong>Web view<\/strong><\/p>\n<\/div>\n<p>A basic UIWebView.<\/p>\n<p>[sourcecode language=&#8221;objc&#8221;]<br \/>\nCGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0);<br \/>\n UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame];<br \/>\n [webView setBackgroundColor:[UIColor whiteColor]];<br \/>\n NSString *urlAddress = @&amp;amp;quot;http:\/\/www.google.com&amp;amp;quot;;<br \/>\n NSURL *url = [NSURL URLWithString:urlAddress];<br \/>\n NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];<br \/>\n [webView loadRequest:requestObj];<br \/>\n [self addSubview:webView];<br \/>\n [webView release];<br \/>\n[\/sourcecode]<\/p>\n<div><strong>Display the Network Activity Status Indicator<\/strong><\/div>\n<p>This is the rotating icon displayed on the iPhone status bar in the upper left to indicate there is background network activity taking place.<\/p>\n<p>[sourcecode language=&#8221;objc&#8221;]<br \/>\nUIApplication* app = [UIApplication sharedApplication];<br \/>\n app.networkActivityIndicatorVisible = YES; \/\/ to stop it, set this to NO<br \/>\n[\/sourcecode]<\/p>\n<div>\n<p><strong>Animation with Series of images<\/strong><\/p>\n<\/div>\n<p>Show a series of images in succession<\/p>\n<p>[sourcecode language=&#8221;objc&#8221;]<br \/>\nNSArray *myImages = [NSArray arrayWithObjects: [UIImage imageNamed:@&quot;myImage1.png&quot;],<br \/>\n[UIImage imageNamed:@&quot;myImage2.png&quot;],<br \/>\n[UIImage imageNamed:@&quot;myImage3.png&quot;],<br \/>\n[UIImage imageNamed:@&quot;myImage4.gif&quot;], &amp;nbsp;nil];<br \/>\nUIImageView *myAnimatedView = [UIImageView alloc];<br \/>\n[myAnimatedView initWithFrame:[self bounds]];<br \/>\nmyAnimatedView.animationImages = myImages;<br \/>\nmyAnimatedView.animationDuration = 0.25; \/\/ seconds<br \/>\nmyAnimatedView.animationRepeatCount = 0; \/\/ 0 = loops forever<br \/>\n[myAnimatedView startAnimating];<br \/>\n[self addSubview:myAnimatedView];<br \/>\n[myAnimatedView release];<br \/>\n[\/sourcecode]<\/p>\n<p><strong>Animation: Move an object<\/strong><\/p>\n<\/div>\n<p>Show something moving across the screen. Note: this type of animation is &#8220;fire and forget&#8221; &#8212; you cannot obtain any information about the objects during animation (such as current position). If you need this information, you will want to animate manually using a Timer and adjusting the x&amp;y coordinates as necessary.<\/p>\n<p>[sourcecode language=&#8221;objc&#8221;]<br \/>\nCABasicAnimation *theAnimation;<br \/>\ntheAnimation=[CABasicAnimation animationWithKeyPath:@&quot;transform.translation.x&quot;];<br \/>\ntheAnimation.duration=1;<br \/>\ntheAnimation.repeatCount=2;<br \/>\ntheAnimation.autoreverses=YES;<br \/>\ntheAnimation.fromValue=[NSNumber numberWithFloat:0];<br \/>\ntheAnimation.toValue=[NSNumber numberWithFloat:-60];<br \/>\n[view.layer addAnimation:theAnimation forKey:@&quot;animateLayer&quot;];<\/p>\n<p>[\/sourcecode]<\/p>\n<p><strong>NSString and int<\/strong><\/p>\n<p>The following example displays an integer&#8217;s value as a text label:<\/p>\n<p>[sourcecode language=&#8221;objc&#8221;]<br \/>\ncurrentScoreLabel.text = [NSString stringWithFormat:@&quot;%d&quot;, currentScore];<br \/>\n[\/sourcecode]<\/p>\n<p><strong>Draggable items<\/strong><\/p>\n<p>Here&#8217;s how to create a simple draggable image.<br \/>\n1. Create a new class that inherits from UIImageView<\/p>\n<p>[sourcecode language=&#8221;objc&#8221;]<br \/>\n@interface myDraggableImage : UIImageView<br \/>\n{<br \/>\n}<br \/>\n[\/sourcecode]<\/p>\n<p>2. In the implementation for this new class, add the 2 methods:<\/p>\n<p>[sourcecode language=&#8221;objc&#8221;]<br \/>\n&#8211; (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event {<br \/>\n  \/\/ Retrieve the touch point<br \/>\n  CGPoint pt = [[touches anyObject] locationInView:self];<br \/>\n  startLocation = pt;<br \/>\n  [[self superview] bringSubviewToFront:self];<br \/>\n}<br \/>\n&#8211; (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event {<br \/>\n   \/\/ Move relative to the original touch point<br \/>\n CGPoint pt = [[touches anyObject] locationInView:self];<br \/>\n CGRect frame = [self frame];<br \/>\n frame.origin.x += pt.x &#8211; startLocation.x;<br \/>\n frame.origin.y += pt.y &#8211; startLocation.y;<br \/>\n [self setFrame:frame];<br \/>\n}<br \/>\n[\/sourcecode]<\/p>\n<p>3. Now instantiate the new class as you would any other new image and add it to your view<\/p>\n<p>[sourcecode language=&#8221;objc&#8221;]<br \/>\ndragger = [[myDraggableImage alloc] initWithFrame:myDragRect];<br \/>\n[dragger setImage:[UIImage imageNamed:@&quot;myImage.png&quot;]];<br \/>\n[dragger setUserInteractionEnabled:YES];<\/p>\n<p>[\/sourcecode]<\/p>\n<div>\n<p><strong>Vibration and Sound<\/strong><\/p>\n<\/div>\n<p>Here is how to make the phone vibrate (Note: Vibration does not work in the Simulator, it only works on the device.)<\/p>\n<p>[sourcecode language=&#8221;objc&#8221;]<br \/>\nAudioServicesPlaySystemSound(kSystemSoundID_Vibrate);<br \/>\n[\/sourcecode]<\/p>\n<p>Sound will work in the Simulator, however some sound (such as looped) has been reported as not working in Simulator or even altogether depending on the audio format. Note there are specific filetypes that must be used (.wav in this example).<\/p>\n<p>[sourcecode language=&#8221;objc&#8221;]<br \/>\nSystemSoundID pmph;<br \/>\nid sndpath = [[NSBundle mainBundle]<br \/>\npathForResource:@&quot;mySound&quot; ofType:@&quot;wav&quot; inDirectory:@&quot;\/&quot;];<br \/>\nCFURLRef baseURL = (CFURLRef) [[NSURL alloc] initFileURLWithPath:sndpath];<br \/>\nAudioServicesCreateSystemSoundID (baseURL, &amp;amp;pmph);<br \/>\nAudioServicesPlaySystemSound(pmph);<br \/>\n[baseURL release];<br \/>\n[\/sourcecode]<\/p>\n<p><strong>Threading<\/strong><\/p>\n<p>1. Create the new thread:<br \/>\n[sourcecode language=&#8221;objc&#8221;]<br \/>\n[NSThread detachNewThreadSelector:@selector(&lt;strong&gt;myMethod&lt;\/strong&gt;) \u00a0 toTarget:self withObject:nil];<br \/>\n[\/sourcecode]<\/p>\n<p>2. Create the method that is called by the new thread:<br \/>\n[sourcecode language=&#8221;objc&#8221;]<br \/>\n&#8211; (void)&lt;strong&gt;myMethod&lt;\/strong&gt; {<br \/>\nNSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];<br \/>\n*** code that should be run in the new thread goes here ***<br \/>\n[pool release];<br \/>\n}<br \/>\n[\/sourcecode]<\/p>\n<p>What if you need to do something to the main thread from inside your new thread (for example, show a loading symbol)?<br \/>\nUse<strong>performSelectorOnMainThread<\/strong>.<br \/>\n[sourcecode language=&#8221;objc&#8221;]<br \/>\n[self performSelectorOnMainThread:@selector(&lt;strong&gt;myMethod&lt;\/strong&gt;) withObject:nil waitUntilDone:false];<br \/>\n[\/sourcecode]<\/p>\n<p><strong>Reading crash logs<\/strong><\/p>\n<\/div>\n<p>For this, see my other post \u00a0<em><a title=\"How to symbolicate iPhone Crash\u00a0Reports;\" href=\"https:\/\/AasimNaseem.com\/wp-content\/uploads\/2011\/05\/10\/how-to-symbolicate-iphone-crash-reports\/\">How to symbolicate iPhone Crash\u00a0Reports;<\/a><\/em><\/p>\n<div>\n<p><strong>Access properties\/methods in other classes<\/strong><\/p>\n<\/div>\n<p>One way to do this is via the AppDelegate:<br \/>\nmyAppDelegate *appDelegate \u00a0 = (myAppDelegate *)[[UIApplication sharedApplication] delegate];<br \/>\n[[[appDelegate rootViewController] flipsideViewController] myMethod];<\/p>\n<div>\n<p><strong>Timers<\/strong><\/p>\n<\/div>\n<p>This timer will call\u00a0<strong>myMethod<\/strong>\u00a0every 1 second.<br \/>\n[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(<strong>myMethod<\/strong>) userInfo:nil repeats:YES];<br \/>\nWhat if you need to pass an object to\u00a0<strong>myMethod<\/strong>? Use the &#8220;userInfo&#8221; property.<br \/>\n1. First create the Timer<br \/>\n[NSTimer scheduledTimerWithTimeInterval:1\u00a0target:self \u00a0selector:@selector(<strong>myMethod<\/strong>) userInfo:<strong>myObject\u00a0<\/strong>repeats:YES];<br \/>\n2. Then pass the NSTimer object to your method:<br \/>\n-(void)<strong>myMethod<\/strong>:<strong>(NSTimer*)timer<\/strong> {<br \/>\n[<strong>[timer userInfo]<\/strong> myObjectMethod];<br \/>\n}<br \/>\nTo stop a timer, use &#8220;invalidate&#8221;:<br \/>\n[myTimer invalidate]; myTimer = nil; \/\/ ensures we never invalidate an already invalid Timer<\/p>\n<div>\n<p><strong>Plist files<\/strong><\/p>\n<\/div>\n<p>Application-specific plist files can be stored in the Resources folder of the app bundle. When the app first launches, it should check if there is an existing plist in the user&#8217;s Documents folder, and if not it should copy the plist from the app bundle.<br \/>\n\/\/ Look in Documents for an existing plist file<br \/>\nNSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);<br \/>\nNSString *documentsDirectory = [paths objectAtIndex:0];<br \/>\nmyPlistPath = [documentsDirectory stringByAppendingPathComponent:<br \/>\n[NSString stringWithFormat: @&#8221;%@.plist&#8221;, plistName] ];<br \/>\n[myPlistPath retain];\u00a0 \/\/ If it&#8217;s not there, copy it from the bundle<br \/>\nNSFileManager *fileManger = [NSFileManager defaultManager];<br \/>\nif ( ![fileManger fileExistsAtPath:myPlistPath] ) {<br \/>\nNSString *pathToSettingsInBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@&#8221;plist&#8221;];<br \/>\n}<br \/>\nNow read the plist file from Documents<br \/>\nNSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);<br \/>\nNSString *documentsDirectoryPath = [paths objectAtIndex:0];<br \/>\nNSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@&#8221;myApp.plist&#8221;];<br \/>\nNSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path];<br \/>\nNow read and set key\/values<br \/>\nmyKey = (int)[[plist valueForKey:@&#8221;myKey&#8221;] intValue];<br \/>\nmyKey2 = (bool)[[plist valueForKey:@&#8221;myKey2&#8243;] boolValue];<br \/>\n[plist setValue:myKey forKey:@&#8221;myKey&#8221;];<br \/>\n[plist writeToFile:path atomically:YES];<br \/>\nThats all from today&#8217;s class;<br \/>\nHappy Development my fellow professionals;<\/p>\n<p><strong>source:\u00a0http:\/\/www.iphoneexamples.com\/<\/strong><\/p>\n<p><img decoding=\"async\" src=\"http:\/\/s06.flagcounter.com\/count\/bDgY\/bg=FFFFFF\/txt=000000\/border=FFFFFF\/columns=6\/maxflags=248\/viewers=0\/labels=1\/pageviews=1\/\" alt=\"free counters\" border=\"0\" \/><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Hello iFellows; Hope all are enjoying your life. Today, there are \u00a0some tips for new iDevelopers. These code chunks will help you out to do some really simple and many-time-usable things. Bring coke and have some light track in iTunes. So here we go;<\/p>\n","protected":false},"author":1,"featured_media":5177,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[22],"tags":[101,140,141,154,336,337,353,546,553,818,886,887,1006,1061,1084],"class_list":["post-2302","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-ios","tag-access-properties-methods-in-other-classes-in-iphone","tag-animation-with-series-of-images","tag-animation-move-an-object","tag-application-frame-size-in-iphone","tag-display-images-in-iphone","tag-display-the-network-activity-status-indicator","tag-draggable-items-iphone","tag-ios-logging","tag-iphon-timer","tag-nsstring-and-int","tag-reading-crash-logs-in-iphone","tag-reading-plist-file-in-iphone","tag-threading","tag-vibration-and-sound","tag-web-view-in-iphone"],"_links":{"self":[{"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/posts\/2302","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/comments?post=2302"}],"version-history":[{"count":4,"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/posts\/2302\/revisions"}],"predecessor-version":[{"id":5182,"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/posts\/2302\/revisions\/5182"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/media\/5177"}],"wp:attachment":[{"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/media?parent=2302"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/categories?post=2302"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/aasimnaseem.com\/blog\/wp-json\/wp\/v2\/tags?post=2302"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}