iOS Code Chunks – Part 2 Aasim Naseem, May 23, 2011 | Read Count: 14,496April 27, 2025 Category: My Tutorials > iOS Hello iFellows; Hope all are enjoying your life. Today, there are some 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; Logging In Xcode, click Run > Console to see NSLog statements. NSLog(@&quot;log: %@ &quot;, myString); NSLog(@&quot;log: %f &quot;, myFloat); NSLog(@&quot;log: %i &quot;, myInt); Display Images Display an image anywhere on the screen, without using UI Builder. You can use this for other types of views as well. CGRect myImageRect = CGRectMake(0.0f, 0.0f, 320.0f, 109.0f); UIImageView *myImage = [[UIImageView alloc] initWithFrame:myImageRect]; [myImage setImage:[UIImage imageNamed:@&quot;myImage.png&quot;]]; myImage.opaque = YES; // explicitly opaque for performance [self.view addSubview:myImage]; [myImage release]; Application Frame Use “bounds” instead of “applicationFrame” — the latter will introduce a 20 pixel empty status bar (unless you want that..) Web view A basic UIWebView. CGRect webFrame = CGRectMake(0.0, 0.0, 320.0, 460.0); UIWebView *webView = [[UIWebView alloc] initWithFrame:webFrame]; [webView setBackgroundColor:[UIColor whiteColor]]; NSString *urlAddress = @&quot;http://www.google.com&quot;; NSURL *url = [NSURL URLWithString:urlAddress]; NSURLRequest *requestObj = [NSURLRequest requestWithURL:url]; [webView loadRequest:requestObj]; [self addSubview:webView]; [webView release]; Display the Network Activity Status Indicator This is the rotating icon displayed on the iPhone status bar in the upper left to indicate there is background network activity taking place. UIApplication* app = [UIApplication sharedApplication]; app.networkActivityIndicatorVisible = YES; // to stop it, set this to NO Animation with Series of images Show a series of images in succession NSArray *myImages = [NSArray arrayWithObjects: [UIImage imageNamed:@"myImage1.png"], [UIImage imageNamed:@"myImage2.png"], [UIImage imageNamed:@"myImage3.png"], [UIImage imageNamed:@"myImage4.gif"], nil]; UIImageView *myAnimatedView = [UIImageView alloc]; [myAnimatedView initWithFrame:[self bounds]]; myAnimatedView.animationImages = myImages; myAnimatedView.animationDuration = 0.25; // seconds myAnimatedView.animationRepeatCount = 0; // 0 = loops forever [myAnimatedView startAnimating]; [self addSubview:myAnimatedView]; [myAnimatedView release]; Animation: Move an object Show something moving across the screen. Note: this type of animation is “fire and forget” — 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&y coordinates as necessary. CABasicAnimation *theAnimation; theAnimation=[CABasicAnimation animationWithKeyPath:@"transform.translation.x"]; theAnimation.duration=1; theAnimation.repeatCount=2; theAnimation.autoreverses=YES; theAnimation.fromValue=[NSNumber numberWithFloat:0]; theAnimation.toValue=[NSNumber numberWithFloat:-60]; [view.layer addAnimation:theAnimation forKey:@"animateLayer"]; NSString and int The following example displays an integer’s value as a text label: currentScoreLabel.text = [NSString stringWithFormat:@"%d", currentScore]; Draggable items Here’s how to create a simple draggable image. 1. Create a new class that inherits from UIImageView @interface myDraggableImage : UIImageView { } 2. In the implementation for this new class, add the 2 methods: - (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event { // Retrieve the touch point CGPoint pt = [[touches anyObject] locationInView:self]; startLocation = pt; [[self superview] bringSubviewToFront:self]; } - (void) touchesMoved:(NSSet*)touches withEvent:(UIEvent*)event { // Move relative to the original touch point CGPoint pt = [[touches anyObject] locationInView:self]; CGRect frame = [self frame]; frame.origin.x += pt.x - startLocation.x; frame.origin.y += pt.y - startLocation.y; [self setFrame:frame]; } 3. Now instantiate the new class as you would any other new image and add it to your view dragger = [[myDraggableImage alloc] initWithFrame:myDragRect]; [dragger setImage:[UIImage imageNamed:@"myImage.png"]]; [dragger setUserInteractionEnabled:YES]; Vibration and Sound Here is how to make the phone vibrate (Note: Vibration does not work in the Simulator, it only works on the device.) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); 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). SystemSoundID pmph; id sndpath = [[NSBundle mainBundle] pathForResource:@"mySound" ofType:@"wav" inDirectory:@"/"]; CFURLRef baseURL = (CFURLRef) [[NSURL alloc] initFileURLWithPath:sndpath]; AudioServicesCreateSystemSoundID (baseURL, &pmph); AudioServicesPlaySystemSound(pmph); [baseURL release]; Threading 1. Create the new thread: [NSThread detachNewThreadSelector:@selector(<strong>myMethod</strong>) toTarget:self withObject:nil]; 2. Create the method that is called by the new thread: - (void)<strong>myMethod</strong> { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; *** code that should be run in the new thread goes here *** [pool release]; } What if you need to do something to the main thread from inside your new thread (for example, show a loading symbol)? UseperformSelectorOnMainThread. [self performSelectorOnMainThread:@selector(<strong>myMethod</strong>) withObject:nil waitUntilDone:false]; Reading crash logs For this, see my other post How to symbolicate iPhone Crash Reports; Access properties/methods in other classes One way to do this is via the AppDelegate: myAppDelegate *appDelegate = (myAppDelegate *)[[UIApplication sharedApplication] delegate]; [[[appDelegate rootViewController] flipsideViewController] myMethod]; Timers This timer will call myMethod every 1 second. [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(myMethod) userInfo:nil repeats:YES]; What if you need to pass an object to myMethod? Use the “userInfo” property. 1. First create the Timer [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(myMethod) userInfo:myObject repeats:YES]; 2. Then pass the NSTimer object to your method: -(void)myMethod:(NSTimer*)timer { [[timer userInfo] myObjectMethod]; } To stop a timer, use “invalidate”: [myTimer invalidate]; myTimer = nil; // ensures we never invalidate an already invalid Timer Plist files 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’s Documents folder, and if not it should copy the plist from the app bundle. // Look in Documents for an existing plist file NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; myPlistPath = [documentsDirectory stringByAppendingPathComponent: [NSString stringWithFormat: @”%@.plist”, plistName] ]; [myPlistPath retain]; // If it’s not there, copy it from the bundle NSFileManager *fileManger = [NSFileManager defaultManager]; if ( ![fileManger fileExistsAtPath:myPlistPath] ) { NSString *pathToSettingsInBundle = [[NSBundle mainBundle] pathForResource:plistName ofType:@”plist”]; } Now read the plist file from Documents NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [paths objectAtIndex:0]; NSString *path = [documentsDirectoryPath stringByAppendingPathComponent:@”myApp.plist”]; NSMutableDictionary *plist = [NSDictionary dictionaryWithContentsOfFile: path]; Now read and set key/values myKey = (int)[[plist valueForKey:@”myKey”] intValue]; myKey2 = (bool)[[plist valueForKey:@”myKey2″] boolValue]; [plist setValue:myKey forKey:@”myKey”]; [plist writeToFile:path atomically:YES]; Thats all from today’s class; Happy Development my fellow professionals; source: http://www.iphoneexamples.com/ Author Profile Aasim Naseem Hey, Thanks for your interest. I’m a PMP, AWS Solutions Architect, and Scrum Master certified professional with 17+ years of hands-on experience leading projects, building teams, and helping organizations deliver software solutions better, faster, and smarter. Outside of work, I’ve got a deep curiosity for history — especially ancient civilizations like Egypt. I also enjoy reflecting on the everyday moments that shape how we live and work. This blog is my space to share insights, lessons, and thoughts from both my professional journey and personal interests. Thanks for reading — and I hope you will find something here that matches your interest. Latest entries IslamJune 6, 2025 | Read Count: 282Economic impact of Eid-ul-Adha PMP CertificationMay 23, 2025 | Read Count: 493Best PMP Study Resources for 2025 (Books, Courses, Tools & More) Agile & FrameworksMay 7, 2025 | Read Count: 463Agile vs Scrum: Finally Understanding the Difference Agile & FrameworksApril 25, 2025 | Read Count: 493When Not To Use Agile: 5 Signs You Need a Different Approach iOS Access properties/methods in other classes in iphoneAnimation with Series of imagesAnimation: Move an objectApplication Frame size in iphoneDisplay Images in iphoneDisplay the Network Activity Status IndicatorDraggable items iphoneios Loggingiphon timerNSString and intReading crash logs in iphonereading plist file in iphoneThreadingVibration and Soundweb view in iphone
iOS Tutorial: How to play with zip files in iOS; January 11, 2013 | Read Count: 12,490April 9, 2025 Category: My Tutorials > iOSHello Dev mates… Hope you are enjoying your work in winters; (: Few days back I was working on a project where I needed to compress some files to create a zip archive; Although my teammate has done much of the work, I just refined some business logic and… Read More
iOS Pattern Colors are Not Supported by the iPhone SDK Prior to 3.0 February 4, 2011 | Read Count: 14,459May 5, 2025 Category: My Tutorials > iOSLast day i opened and compiled an old project of iPhone; I’m using Xcode 3.2.5 with iOS 4.2 on Mac OS X 10.6.6; When i complied that project I got the following error in multiple xib files Pattern colors are not supported by the iPhone SDK… Read More
iOS Storage Issue with iOS-5 And iCloud; February 2, 2012 | Read Count: 13,485April 27, 2025 Category: My Tutorials > iOSHello everyone .. Now a days, we are noticing that many people are getting rejection from AppStore due to storage issue; I looked into this issue and here are my findings regarding iOS-5 and iCloud; When we install our application in device, we have three main directories… Read More
I have an image in a webView, but it keeps bouncing up or down when swiped instead of changing to the next image (a gallery app) It works fine in iPhone, the image is firmly placed and responds to swipe gesture properly. The iPad version has the swipe gesture activated in the toolbar (not the webView) ! What can I do? Help! Reply
can you describe your problem in little more detail? What i have understood is an image in webview is not responding well to swap gesture, in iPad version; is that? Reply