200810 - iPhone Tutorial


Published on

Using XCode 3.0 under Mac OS X 10.5 as our IDE, and Objective-C and iPhone API as our programming tools we will create iPhone applications (from basic to medium level), which finally can be, load into an iPhone. We’ll start with the classical “Hello World” and continue to develop applications using graphical user interfaces, handling multi-touch and detect motion, communication
with web application, and different media.

Published in: Technology, News & Politics
1 Comment
  • Apple’s New iPod Touch
    A Worthy Innovation or a High Priced Techno Overload?
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

200810 - iPhone Tutorial

  1. 1. iPhone SDK a Ki k start iPh SDK: Kick t t Using Xcode 3.1 Developer Tools for iPhone OS Copyright is held by the author/owner(s). OOPSLA 2008, October 19–23, 2008, Nashville, Tennessee, USA. ACM 978-1-60558-220-7/08/10.
  2. 2. Agenda 1. 1 Introduction Apple Developer Connection, iPhone platform; Tools for development;. 2. Objective-C language syntaxes; memory management; design patterns. 3. Creating a new project simple “Hello World” example; simple drawing; multi touch events; configuration list p p p g g 4. UI components windows, views and view controllers; using Interface Builder. 5. iPhone in action accelerometers; localization; media; openGL ES 6. Exercises and references 2
  3. 3. Our Objective Using XCode 3.1 under Mac OS X 10.5 as our IDE, and Objective-C and iPhone API as our programming t l we will create iPh i tools ill t iPhone applications (f li ti (from b i t medium basic to di level) which finally can be loaded into an iPhone. We’ll start with the classical “Hello World” d W ld” and continue t d ti to develop applications using graphical user i t f l li ti i hi l interfaces, handling h dli multi-touch and detect motion, communication with web application, and different media. di 3
  4. 4. Material Google Groups :: OOPSLA08 iphone G l G i h http://groups.google.com/group/oopsla08-iphone htt // l / / l 08 i h 4
  5. 5. Introduction I t d ti 1.1.
  6. 6. What is it ? iPhone is a pretty new device that involve several t h l i ( h iPh i tt d i th t i l l technologies (phone, video, id audio, images, and web among others). The best in 2007 year according to Times Magazine, Big winner in the 2008 British Technology Awards. Claimed the award for Gadget of the Year , won the Best Mobile Technology, Most Stylish Technology, and Technological Innovation of the Year awards. It has captive the interest of different types of users and created a new emerging market in various environments. Today thousands of programmers want to provide applications on the iPhone. It includes multi touch interface, sensors and a camera. 6
  7. 7. Go ahead 7
  8. 8. Developer Connection 8
  9. 9. iPhone SDK • Sample code Documentation • Reference libraries • Coding how-to • UIKit • Foundation Frameworks • Media • OpenGL / Quartz / Core Graphics p p • Xcode, Tools • Interface Builder • iPhone Simulator 9
  10. 10. Install 1. Boot into a partition with the Mac OS X v10.5.3 installed. 2. Download the iPhone SDK software. 3. Double-click on iPhone SDK installer package. 4. Follow the instructions in the Installer. 5. To i t ll Xcode 3.1 in directory other th th d f lt /D 5 T install X d 3 1 i a di t th than the default /Developer, you must specify a l t if new <Xcode> directory name on the "Custom Install" pane; e.g. Xcode3.1. Select the folder icon under "Location" next to the "Developer Tools Essentials" package name. Select "Other..." at the top of the pop-up. Navigate to the location for the new <Xcode> folder Select "New Folder". folder. New Folder 10
  11. 11. Install Enter folder E t a f ld name i th "N in the "New F ld " window; e.g. X d 3 1 S l t "C t " Folder" i d Xcode3.1. Select "Create". Finally, select "Choose" in the "Install Xcode Tools" pane. 6. If you need to install Mac OS X 10.3.9 Support or WebObjects, you must select "Customize", and check those packages on the "Custom Install" panel. 7. Authenticate as the administrative user. The first user you create when setting up Mac y g p OS X has administrator privileges by default. Developer applications such as Xcode, Instruments, and Interface Builder are installed in <Xcode>/Applications. 11
  12. 12. Uninstall To uninstall Xcode developer tools on the boot volume along with the <Xcode> directory from a directory, Terminal window type: $ sudo <Xcode>/Library/uninstall-devtools --mode=all If you just want to remove the underlying developer content on the boot volume, but leave the <Xcode> directory and supporting files untouched, from a Terminal window type: $ sudo <Xcode>/Library/uninstall-devtools --mode=systemsupport If you just want to just remove the UNIX development support on the boot volume, but leave the <Xcode> directory and supporting files untouched, from a Terminal window type: $ sudo <Xcode>/Library/uninstall-devtools --mode=unixdev Finally, to just uninstall the <Xcode> directory you can simply drag it to the trash, or from a Terminal window type: $ sudo <Xcode>/Library/uninstall-devtools --mode=xcodedir <Xcode>/Library/uninstall devtools mode xcodedir 12
  13. 13. Time to Work 1 Install iPhone SDK
  14. 14. Tools for D T l f Development l t 1.2
  15. 15. Tools We are going to be working with: Xcode Interface Builder iPhone Simulator And also need to consider Instruments 15
  16. 16. Xcode The f Th focus of your development experiences is th X d application. X d i f d l t i i the Xcode li ti Xcode is an integrated development environment (IDE) that provides all of the tools you need to create and manage your iPhone projects and source files, build your code into an executable, and run and debug y , g your code either in iPhone simulator or on a device. To create a new iPhone application, you start by creating a new project in Xcode. A project manages all of the information associated with your application, including the source files, build settings, and rules needed to put all of the pieces t f th i together. The heart of every Xcode project is th project windows. th Th h t f X d j t i the j t i d 16
  17. 17. Xcode 17
  18. 18. Xcode editor, Xcode comes with an advanced text editor which supports features such as code completion, syntax coloring, code folding (to hide code blocks temporarily), and inline annotations for errors, warnings, and notes. The build system in Xcode provides both appropriate default settings and the ability to customize the environment. environment And if you need documentation the Research Assistant provides documentation, context-sensitive documentation while the Xcode documentation window lets you browse and search for information. When you build your application in Xcode, you have a choice of building it for iPhone simulator or for a device. The simulator provides a local environment for testing your applications to make sure they behave essentially the way you want. After you are satisfied with your application’s basic behavior, you can tell Xcode to build it and run it on an iPhone or iPod touch connected to your computer. Running on a device provides the ultimate test environment, and Xcode lets you attach the built-in debugger to the code running on the device. 18
  19. 19. Xcode 19
  20. 20. Interface Builder Interface Builder is the tool you use to assemble your application s user interface application’s visually. Using Interface Builder, you assemble your application’s window by dragging and dropping preconfigured components onto it. The components include standard system controls such as switches, text fields, and buttons, and also custom views to represent the views your application provides. After you’ve placed the th components on the window’s surface, you can position th t th i d ’ f iti them b d by dragging th i them around, configure their attributes using the inspector, and establish the relationships between those objects and your code. When your interface looks the way you want it, you save the contents to a nib file, which is a custom resource file format. The nib files you create in Interface Builder contain all the information that the UI Kit needs to recreate the same objects in your application at runtime. Loading a nib file creates runtime versions of all the objects stored in the file configuring them exactly file, as they were in Interface Builder. It also uses the connection information you specified to establish connections between the newly created objects and any existing objects in your application. These connections provide your code with pointers to the nib-file objects and also provide the information the objects themselves need t communicate user actions t your code. th l d to i t ti to d 20
  21. 21. Interface Builder 21
  22. 22. Instruments To ensure that you deliver the best user experience for your software the software, Instruments environment lets you analyze the performance of your iPhone applications while running in the simulator or on a device. Instruments gathers data from your running application and presents that data in a graphical display called the timeline. You can gather data about your application’s memory usage, disk activity, network activity, and graphics performance. Th ti li view can di l ti it t k ti it d hi f The timeline i display all of the different types of information side by side, letting you correlate the overall behavior of your application, not just the behavior in one specific area. To get even more detailed information, you can also view the detailed samples that Instruments g gathers. In addition to providing the timeline view, Instruments provides tools to help you analyze your application’s behavior over time For example the Instruments window application s time. example, lets you store data from multiple runs so that you can see whether your application’s behavior is actually improving or whether it still needs work. You can save the data from these runs in an Instruments document and open them at any time. 22
  23. 23. Instruments 23
  24. 24. Instruments 24
  25. 25. Time to Work 2 XCode, XC d IB and Instruments example dI t t l
  26. 26. iPhone Pl tf iPh Platform 1.3
  27. 27. Introduction iPhone Pl tf iPh Platform comprises th operating system and t h l i th t you use i the ti t d technologies that to run applications natively on iPhone and iPod touch devices and iPhone OS. Although it shares a common heritage and many underlying technologies with Mac OS X, iPhone OS was designed to meet the needs of a mobile environment, where user’s needs are slightly different. Existing Mac OS X developers will find many familiar technologies, but they’ll also find technologies that are available only on iPhone OS such as the Multi-Touch OS, interface and accelerometer support. 27
  28. 28. Key Concepts iPhone SDK supports the creation of graphically oriented applications that run graphically-oriented natively in iPhone OS. Take advantage of built-in hardware such as the accelerometers, camera, and graphics hardware hardware. All of the application’s data is displayed in a single window. This has lead to the creation of new views and controls that allow you to present your application’s data in an organized manner manner. The event-handling model in iPhone OS also represents a significant departure from traditional desktop applications. Instead of relying on the traditional mouse and keyboard events iPhone OS introduces the idea of touch events events, events. User experience. Memory management without a “garbage collector”. garbage collector 28
  29. 29. Architecture Layers L Cocoa Touch Media Core Services Core OS 29
  30. 30. Layers Core OS and Core Services l C dC S i layers contain th f d t i the fundamental i t f t l interfaces f for iPhone OS, including those used for accessing files, low-level data types, Bonjour services, network sockets, and so on. These interfaces are mostly C based and include technologies such as: g Core Foundation, CFNetwork, SQLite, Access to POSIX threads, UNIX sockets Among others. 30
  31. 31. Layers Media layer contains th f d M di l t i the fundamental t h l i used t support 2D and 3D t l technologies d to t d drawing, audio, and video. This layer includes the C-based technologies: OpenGL ES, Quartz, and Core Audio, Core Animation, an advanced Objective-C based animation engine. 31
  32. 32. Layers In the Cocoa Touch layer most of the technologies use Objective C The layer, Objective-C. frameworks at these layers provide the fundamental infrastructure used by your application. For example: the Foundation framework provides object-oriented support for collections, file management, network operations, and more. the UIKit framework provides the visual infrastructure for your application, including classes for windows, views, controls, and the controllers that manage those objects. Other frameworks at this level give you access to the user’s contact and photo information and to the accelerometers and other hardware features of the device. 32
  33. 33. Starting Point The t ti Th starting point for any new project is the C i tf j t i th Cocoa T Touch l h layer, and th UIKit d the framework in particular. The higher-level frameworks make it easy to support standard system behaviors with the least amount of effort on your part. 33
  34. 34. Time to Work 3
  35. 35. Objective-C Language Obj ti C L 2
  36. 36. Objective-C Objective C The Objective-C language is a simple computer language designed to enable Objective C sophisticated object-oriented programming. Objective-C extends the standard ANSI C language by providing syntax for defining classes, methods, and properties, as well as other constructs that promote dynamic extension of classes. The class syntax and design are based mostly on Smalltalk, one of the first object-oriented programming l i languages. If you have programmed with object-oriented languages before, the following information should help you learn the basic syntax of Objective-C. Many of the traditional object-oriented concepts, such as encapsulation, inheritance, and object oriented polymorphism, are all present in Objective-C. There are a few important differences, but those differences are called out in this article and more detailed information is available if you need it. If you have never programmed using an object oriented language before you need object-oriented before, to have at least a basic understanding of the associated concepts before proceeding. The use of objects and object-oriented constructs is fundamental to the design of iPhone applications, and understanding how they interact is critical to creating your applications. 36
  37. 37. Files Extension Source Type .h Header files. Header files contain class, type, function, and constant declarations. .m Source files. This is the typical extension used for source files and can contain both Objective-C and C code. .mm Source files. A source file with this extension can contain C++ code in addition to Objective-C and C code. This t Thi extension should be used only if you actually refer to C++ i h ld b d l t ll f t C classes or features from your Objective-C code. 37
  38. 38. #import When Wh you want to include header fil i your source code, you can use th t t i l d h d files in d the standard #include compiler directive but Objective-C provides a better way. The #import directive is identical to #include, except that it makes sure that the same file is never included more than once. The Objective-C samples and documentation all prefer the use of #import, and your own code should too. 38
  39. 39. Strings The NSSt i Th NSString class provides an object wrapper f strings th t has all of th l id bj t for t i that h ll f the advantages you would expect, including built-in memory management for storing arbitrary-length strings, support for Unicode, printf-style formatting utilities, and more. Because such strings are used commonly though, , g y g , Objective-C provides a shorthand notation for creating NSString objects from constant values. To use this shorthand, all you have to do is precede a normal, double-quoted string with the @ symbol, as shown in the following examples: NSString* myString = @”Hello Worldn"; NSString* anotherString = [ NSString stringWithFormat:@"%d %s", 1, @"String” ]; 39
  40. 40. Note Cocoa F C Framework i d i d f k is derived from th N XTSTEP and OPENSTEP the NeXTSTEP d programming environments developed by NeXT in the late 1980s. Apple acquired NeXT in December 1996, and subsequently went to work on the Rhapsody operating system that was supposed to be the direct successor of OPENSTEP. The OPENSTEP base of libraries and binary support was termed Yellow Box. Rhapsody evolved into Mac OS X, and the Yellow Box became Cocoa. As a result, Cocoa classes begin with the acronym "NS" (standing either for the NeXT-Sun NeXT Sun creation of OPENSTEP or for the original proprietary term for the OPENSTEP, OPENSTEP framework, NeXTSTEP): NSString, NSArray, etc. 40
  41. 41. Class The specification of a class in Objective C requires two distinct pieces: the Objective-C interface and the implementation. The interface portion contains the class declaration and defines the instance variables and methods associated with the class class. The implementation portion contains the actual code for the methods of the class. The class declaration always begins with the @interface compiler directive and ends with the @end directive. Following the class name (and separated from it by a colon) is the name of the parent class. The instance (or member) variables of the class are declared in a code block that is delineated by braces ({ and }) }). Following the instance variable block is the list of methods declared by the class. A semicolon character marks the end of each instance variable and method declaration. 41
  42. 42. Class @interface MyClass : NSObject { int count; id data; NSString* name; } - (id)initWithString:(NSString *)aName; + (MyClass *)createMyClassWithString: (NSString *) aName @end 42
  43. 43. Class @implementation MyClass - (id)initWithString:(NSString *) aName { if (self = [super init]) { count = 0; data = nil; name = [aName copy]; return self; } } + (MyClass *)createMyClassWithString: (NSString *) aName { return [[[self alloc] initWithString:aName] autorelease]; } @end 43
  44. 44. Methods A class in Objective C can declare two types of methods: instance methods Objective-C and class methods. An instance method is a method whose execution is scoped to a particular instance of the class In other words before you call an instance method you class. words, method, must first create an instance of the class. Class methods, by comparison, do not require you to create an instance. The declaration of a method consists of the method type identifier, a return type, one or more signature keywords, and the parameter type and name information. The colon characters declare the presence of a parameter. If a method has no parameters, you omit the colon after the first (and only) signature keyword. In this example, the method takes two parameters. 44
  45. 45. Methods -(void)insertObject:(id)anObject atIndex:(NSUInteger)index (void)insertObject:(id)anObject … [ y [myArray insertObject:anObj atIndex:0]; y j j ] Method Type Return Type Signature keywords Parameter Types Parameter Names 45
  46. 46. Properties Properties are a convenience notation used to replace accessor method declarations. Properties do not create new instance variables in your class declaration. They are simply a shorthand for defining methods that access existing instance variables. Classes that expose instance variables can do so using the property notation instead of using getter and setter syntax. Classes can also use properties to expose “virtual” instance variables—that is, pieces of data that are computed dynamically and not actually stored in instance variables. variables Practically speaking, properties reduce the amount of redundant code you have to write. Because most accessor methods are implemented in similar ways, properties eliminate the need to provide a distinct getter and setter method for each instance variable exposed in the class. Instead, you specify the behavior you want using the property declaration and then synthesize actual getter and setter methods based on that declaration at compile time. 46
  47. 47. Propierties @property BOOL flag; @property (copy) NSString* nameObject; //Copy the object during assignment. @property ( p p y (readonly) UIView* rootView; y) // Create only a g y getter method. … myObject.flag = YES; CGRect viewFrame = myObject.rootView.frame; 47
  48. 48. Protocols and Delegates A protocol declares methods that can be implemented by any class Protocols are not classes class. themselves. They simply define an interface that other objects are responsible for implementing. When you implement the methods of a protocol in one of your classes, your class is said to conform to that protocol. In iPhone OS protocols are used frequently to implement delegate objects A delegate object is OS, objects. an object that acts on behalf of, or in coordination with, another object. By example, the UIApplication class implements the required behavior of an application. Instead of forcing you to subclass UIApplication to receive simple notifications about the current state of the application, the UIApplication class delivers those notifications by calling specific methods of its assigned delegate object. An object that implements the methods of the UIApplicationDelegate protocol can receive those notifications and provide an appropriate response. The dec a a o o a p o oco looks s e declaration of protocol oo s similar to that o a c ass interface, with the e cep o s that a o a of class e ace, e exceptions a protocols do not have a parent class and they do not define instance variables. In the case of many delegate protocols, adopting a protocol is simply a matter of implementing the methods defined by that protocol. There are some protocols that require you to state explicitly that y support the p p y you pp protocol, and p , protocols can specify both required and optional p y q p methods. 48
  49. 49. Time to Work 4 A classical Fraction class
  50. 50. Fraction.h Fraction h <Foundation/NSObject.h> #import <Foundation/NSObject h> @interface Fraction: NSObject { int numerator; int denominator; } -(void) print; -(void) setNumerator: (int) d; -(void) setDenominator: (int) d; -(int) numerator; -(int) denominator; @end 50
  51. 51. Fraction.m Fraction m "Fraction.h" #import "Fraction h" #import <stdio.h> @implementation Fraction -(void) print { printf( "%i/%i", numerator, denominator ); } -(void) setNumerator: (int) n { numerator = n; } -(void) setDenominator: (int) d { denominator = d; } -(int) denominator { return denominator; } -(int) numerator { return numerator; } @end 51
  52. 52. main.m main m p #import <stdio.h> #import "Fraction.h" int main( int argc, const char *argv[] ) { Fraction *frac = [[Fraction alloc] init]; [[ ] ] [frac setNumerator: 1]; [frac setDenominator: 3]; printf( "The fraction is: " ); [frac print]; printf( "n" ); [f l ] [frac release]; return 0; } 52
  53. 53. Creating C ti an A li ti Application 3.1
  54. 54. Introduction At a high l hi h level, th process f creating an iPh l the for ti iPhone application i similar t th t li ti is i il to that for creating a Mac OS X application. Both use the same tools and many of the same basic libraries. Despite the similarities, there are also significant differences. An iPhone is not a desktop computer; it has a different purpose and requires a very different design approach. That approach needs to take advantage of the strengths of iPhone OS and forego features that might be irrelevant or impractical in a mobile environment. The smaller size of the iPhone and iPod touch screens also means that your application's user interface should be well organized and always focused on the information the user needs most. 54
  55. 55. Steps 1. Main 2. Delegate 3. 3 Views 55
  56. 56. Views 1. Main 2. Delegate 3. 3 Views 56
  57. 57. Steps Initializing the I iti li i th application li ti Displaying a window Drawing custom content Handling touch events 57
  58. 58. Project Window Based Window-Based 1. Foundation 2. CoreGraphics 3. 3 UIKit 58
  59. 59. main.m main m int main(int argc, char *argv[]) { NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; int retVal = UIApplicationMain(argc, argv, nil, nil); [pool release]; return retVal; } 59
  60. 60. Application Delegate One f th O of the most important architectural d t il of your project i d fi i th ti t t hit t l details f j t is defining the application delegate object, which is instantiated from a class you provide in your project. The application delegate class declares its interface in a *.h file and defines its implementation in a *.m file. Delegate is responsible of creating the window and views of the apps: using interface Builder or programatically. 60
  61. 61. Application Delegate #import <UIKit/UIKit.h> @class MiVista; @interface HolaMundoAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; MiVista *vista; } @property (nonatomic, retain) UIWindow *window; @property (nonatomic, retain) MiVista *vista; @end 61
  63. 63. Create a view (programatically) import <UIKit/UIKit.h> i # i / i h @interface MiVista : UIView { UILabel *miTexto; } @property (nonatomic, retain) UILabel *miTexto; @end 63
  64. 64. Create a view (programatically) MiVista.h ##import "MiVista h” @implementation MiVista(id)initWithFrame:(CGRect)rectangulo { -(id)initWithFrame:(CGRect)rectangulo { [super initWithFrame:rectangulo]; self.backgroundColor =[UIColor whiteColor]; lf b k dC l [UIC l hit C l ] CGRect contenidoRectangulo = self.frame; CGFloat margenIzquierdo = 90.0; CGFloat anchoTextField = contenidoRectangulo.size.width * 0.72; CGFloat posicionTextField = (contenidoRectangulo.size.width - anchoTextField)/2.0; CGRect etiqueta = CGRectMake(posicionTextField,margenIzquierdo,anchoTextField,FONT_SIZE* HEIGHT_MULTIPLIER); UILabel *miTexto = [[UILabel alloc] initWithFrame:etiqueta]; miTexto.text = @"Hola Mundo"; miTexto.font = [UIFont systemFontOfSize:FONT_SIZE]; miTexto.textColor = [UIColor redColor]; miTexto.textAlignment = UITextAlignmentCenter; [self addSubview:miTexto]; [miTexto release]; return self;} } -(void)dealloc { [super dealloc]; } @end 64
  65. 65. Touch E T h Events t 3.2
  66. 66. Handling Touch Events UIView are part of UIR All UIVi t f UIResponder and can i l d d implement E t Event “li t t “listener” ” - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event; )touches )event; - (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event; - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event; 66
  67. 67. Handling Touch Events 67
  68. 68. Plist file Pli t fil 3.3
  69. 69. plist file <?xml version="1.0" encoding="UTF-8"?> l i "1 0" di " 8" <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>en</string> <key>CFBundleDisplayName</key> <string>${PRODUCT_NAME}</string> <key>CFBundleExecutable</key> <string>${EXECUTABLE_NAME}</string> y y <key>CFBundleIconFile</key> <string>Icon.png</string> <key>CFBundleIdentifier</key> <string>com.yourcompany.${PRODUCT_NAME:identifier}</string> 69
  70. 70. plist file <key>CFBundleInfoDictionaryVersion</key> k dl f i i i /k <string>6.0</string> <key>CFBundleName</key> <string>${PRODUCT_NAME}</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleSignature</key> <string>????</string> <key>CFBundleVersion</key> <string>1.0</string> <key>UIStatusBarHidden</key> <true/> <key>NSMainNibFile</key> <string>MainWindow</string> </dict> </plist> 70
  71. 71. Time to Work 5
  72. 72. UI components 4.1
  73. 73. Interface Builder File’s Owner, it i a proxy object. It i a Fil ’ O is bj t is placeholder for the object responsible of manage the content. The library 73
  74. 74. View-Based View Based Project Create C t a view-based project i b d j t ViewController f C files are created automatically (h, m y xib) Open ViewController.xib: add text field, a label, and a button. Add a UIImage if you want, to complete the GUI. 74
  75. 75. Connecting the UI with the code STEP 1: open ViewController h: ViewController.h: #import <UIKit/UIKit.h> @interface IBViewController : UIViewController { IBOutlet UITextField *txtName; IBOutlet UILabel *lbHello; } @property (nonatomic, retain) IBOutlet UITextField *txtName; @property (nonatomic, retain) IBOutlet UILabel *lbHello; - (IBAction) updateText:(id) sender; @end 75
  76. 76. IBOutlet and IBAction IBOutlet is a null-defined macro, which the C preprocessor An outlet is an instance variable that identifies an object IBAction, like IBOutlet, is a null defined macro, which the C preprocessor removes at compile time 76
  77. 77. Connecting the UI with the code STEP 2: open ViewController.xib: 2 Vi C t ll ib Click in the view (outside button, label and so) : connections inspector : new reference outlet : and connect to file’s owner proxy object. Click in the textfield : connections inspector : new reference outlet : and connect to file’s owner proxy object. Click in the label : connections inspector : new reference outlet : and connect to file’s owner proxy object. Click in the label : connections inspector : Touch up inside: and connect to file’s owner proxy object. 77
  78. 78. Connecting the UI with the code STEP 3: open ViewController.m: 3 Vi C t ll #import "IBViewController.h” @implementation IBViewController@synthesize txtName, lbHello; -(IBAction) updateText:(id) sender {NSString *text; if ([txtName.text length] == 0) { text = @"escibe tu nombre"; } else { text = [[NSString alloc] initWithFormat:@"Hola %@!", txtName.text]; } lbHello.text = text;[text release]; } - (void)dealloc { [super dealloc]; } @end 78
  79. 79. Navigation Na igation Based 4.2
  80. 80. Navigation-Based Navigation Based Project Create C t a navigation-based project i ti b d j t ViewController f C files are created and include a UITable component automatically (h, m y xib) Execute the code 80
  81. 81. Updating UITable data At RootViewController.m R tVi C t ll 81
  82. 82. UITable and more views together One O more View Vi Double click RootViewController.xib to open Interface Builder Click un File New : and select View C Add a Label or TextView to the View Save it inside the project directory. Close Interface Builder and drag the new XIB file to Resources Folder. 82
  83. 83. UITable and more views together One more ViewController File : New : and select UIViewController subclass. You need a new m and h file. In the h file add a new outlet for the textview: #import <UIKit/UIKit.h> @interface VistaDosViewController : UIViewController { IBOutlet UITextView* texto; } @property (nonatomic, retain) IBOutlet UITextView *texto; @ i i i @end Open IB, select TextView : conections inspector : new outlet, and link with File’s owner (and select the corresponding ViewController) 83
  84. 84. UITable and more views together One O more ViewController ( m fil ) Vi C t ll file) 84
  85. 85. Associate view and view controller Double li k in the file VistaDos.xib D bl click i th fil Vi t D ib Click File’s Owner, then click tools -> identity inspector Select VistaDosViewControler in the dropdown class S C Click in any place of the view to select it, next tools – connections inspector, new reference outlet, and drag to file owner. g 85
  86. 86. Manipulation Data Manip lation 4.3
  87. 87. Simple Object Create C t a new Fil of NSObj t subclass t File f NSObject b l type. #import <UIKit/UIKit.h> @interface Fruta : NSObject { NSString *nombre;NSString *descripcion; } @property(nonatomic, copy) NSString *nombre; @property(nonatomic, copy) NSString *descripcion; -(id) initWithNombre:(NSString*)n descripcion:(NSString *) d; @end #import "Fruta.h“ @implementation Fruta { @synthesize nombre, descripcion; -(id) initWithNombre:(NSString*)n descripcion: (NSString )d {self nombre (NSString*)d {self.nombre = n; self.descripcion = d; return self;} @end If you want to create a method constructor this must return “self”. 87
  88. 88. An Array Open the Delegate.h Fil O th D l t h File: #import <UIKit/UIKit.h> @interface TablaAppDelegate : NSObject <UIApplicationDelegate> { UIWindow *window; UINavigationController *navigationController; NSMutableArray *frutas; } @p p y (nonatomic, retain) IBOutlet UIWindow *window; @property ( , ) ; @property (nonatomic, retain) IBOutlet UINavigationController *navigationController; @property (nonatomic, retain) NSMutableArray *frutas; @end Create array and add a property 88
  89. 89. An Array Open the Delegate.m File: #import "TablaAppDelegate.h“ #import "RootViewController.h“ #import "Fruta.h“ @implementation TablaAppDelegate @synthesize window; @ th i i d @synthesize navigationController; @synthesize frutas; -(void)applicationDidFinishLaunching:(UIApplication *)application { Fruta *manzana = [[Fruta alloc] initWithNombre:@"Manzana" descripcion:@"rojas y verdes son deliciosas!"]; Fruta *naranja = [[Fruta alloc] initWithNombre:@"Naranja" descripcion:@"ideal para jugo! ]; naranja initWithNombre:@ Naranja descripcion:@ ideal jugo!"]; Fruta *melon = [[Fruta alloc] initWithNombre:@"Melon" descripcion:@"una fruta poco recomendable!"]; self.frutas =[[NSMutableArray alloc] initWithObjects:manzana, naranja, melon, nil]; // Configure and show the window [window addSubview:[navigationController view]]; [window makeKeyAndVisible]; } -(void)applicationWillTerminate:(UIApplication *)application { // Save data if appropriate } -(void)dealloc { [navigationController release]; [window release]; [super dealloc]; } @end 89
  90. 90. Principal ViewControler Open the RootViewController.m File: -(NSInteger)tableView:(UITableView *) tableView numberOfRowsInSection:(NSInteger)section { TablaAppDelegate *appDelegate = (TablaAppDelegate*)[[UIApplication sharedApplication] delegate]; return appDelegate.frutas.count; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; } TablaAppDelegate *appDelegate = (TablaAppDelegate )[[UIApplication sharedApplication] delegate]; appDelegate (TablaAppDelegate*)[[UIApplication Fruta *f = (Fruta*) [appDelegate.frutas objectAtIndex:indexPath.row];[cell setText:f.nombre]; // [cell setText:@"Hola Mundo"];// Set up the cell return cell;} -(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { // Navigation logic -- create and push a new view controllerTablaAppDelegate *appDelegate = (TablaAppDelegate )[[UIApplication (TablaAppDelegate*)[[UIApplication sharedApplication] delegate]; Fruta *fruta = (Fruta*) [appDelegate.frutas objectAtIndex:indexPath.row];I f (self.vistaDosViewController == nil) { VistaDosViewController *vistaDos = [[VistaDosViewController alloc] initWithNibName:@"VistaDos" bundle:[NSBundle mainBundle]]; self.vistaDosViewController = vistaDos;[vistaDos release];} [self.navigationController pushViewController:self vistaDosViewController [self navigationController pushViewController:self.vistaDosViewController animated:YES]; self.vistaDosViewController.title = [fruta nombre]; [self.vistaDosViewController.texto setText:[fruta descripcion]]; } 90
  91. 91. Time to Work 6
  92. 92. Working more SQLite SQLit iPphone suport the use of databases SQLite. f SQ One interesting work outside of this presentation is to convert this simple Array based table in a database application. y pp 92
  93. 93. iPhone in action 5
  94. 94. Using the Accelerometers Provide input for the system and for your own custom applications Measures changes in velocity along a single linear axis. iPhone have three accelerometers in a 3D space, to detect motion in any direction. p y By tracking which accelerometers are registering acceleration, and the extent of that acceleration, you can detect the physical orientation of a device in 3D space. You can then apply this orientation and its changes as inputs to your application. The UIViewController class provides the infrastructure needed to rotate your interface and adjust the position of views automatically in response to orientation changes. UIAccelerometer object in UIKit allow you t access to the raw accelerometer d t UIA l t bj t i ll to t th l t data directly. This object reports the current accelerometer values. You can also use the data to detect the device's orientation or to detect other types of instantaneous motion, such as the user shaking the device back and forth. You can then use this information as input to a g p game or other application. pp 94
  95. 95. Using the Accelerometers Classes, Classes objects and methods Every application h E li ti have an UIA l UIAcelerometer object. t bj t To get an instance of this class, you use sharedAccelerometer method of UIAccelerometer. Whit this object you set (updateInterval) the reporting interval (minum 10 miliseg = 100 Hz) and a delegate to receive acceleration events (UIAccelerometerDelegate). Use accelerometer:didAccelerate : method to process accelerometer data. - (void)accelerometer:(UIAccelerometer *) accelerometer didAccelerate:(UIAcceleration *) acceleration. didA l t (UIA l ti l ti UIAccelerationValue object could store the value of an axis. 95
  96. 96. Using the Accelerometers Isolating the Gravity Component From Acceleration Data (detect changes of orientation) using a low- low pass filter. accelX, accelY and accelZ are member variables that settle out quickly and respond slowly to sudden changes in motion. Isolating Instantaneous Motion From Acceleration Data (movement changes) using a high-pass filt I l ti I t t M ti F A l ti D t ( t h ) i hi h filter Current Device Orientation Use UIDevice l U UID i class methods: th d beginGeneratingDeviceOrientationNotifications current orientation is stored at orientation properties UIDeviceOrientationChangeNotification posted whenever orientations change UIDeviceOrientation constants (landscape or portrait, face up or down) portrait Disabling orientation notifications Use the endGeneratingDeviceOrientationNotifications 96
  97. 97. Example 97
  98. 98. Getting the User's Current Location User s go. Devices that run iPhone OS are meant for users on the go Therefore the software you write for these devices should also take this fact into account. And because the Internet and web make it possible to do business anywhere, being able to tailor information for the user's current location can make for a compelling user experience. The Core Location framework monitors signals coming from cell phone towers and Wi-Fi hotspots and uses them to triangulate the user's current position. You can use this framework to grab an initial location fix only or you can be notified whenever only, the user's location changes. With this information, you can filter the information your application provides or use it in other ways. Retrive Current Location. Create an instance of CLLocationManager class. To begin receiving notifications, assign a delegate and call the startUpdatingLocation method. When new location information is available the manager notifies the delegate. 98
  99. 99. Playing Audio and Video iPhone OS supports audio features in your application through the Core Audio and OpenAL frameworks, and provides video playback support using the Media Player framework. Core Audio provides an advanced interface for playing, recording, and manipulating sound and f parsing streamed audio. Y can use i to play b k simple sound d d for i d di You it l back i l d effects or multichannel audio, mix sounds and position them in an audio field, and even trigger the vibrate feature of an iPhone. If you are a game developer and already have code that takes advantage of OpenAL, you can use your code in iPhone OS to position and play back audio in your games. The Media Player framework is what you use to play back full-screen video files. This framework supports the playback of many standard movie file formats and gives you control over the playback environment, including whether to display user controls and how to configure the aspect ratio of video content content. Game developers might use this framework to play cut scenes or other prerendered content, while media-based applications can also use this framework to play back movie files. 99
  100. 100. Exercises and References 6
  101. 101. iPhone Dev Center http://developer.apple.com/iphone 101