Mobile APPs con Objective-C (iOS 3.1+) - Day 02/02

486 views

Published on

Technical speech per objectivec e ios versione 3.1.

Argomenti trattati:
~ interfacce grafiche
~ eventi
~ Foundation.framework
~ persistenza dati
~ librerie
~ esempi

Source code / esempi: https://github.com/elpsk

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
486
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
3
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Mobile APPs con Objective-C (iOS 3.1+) - Day 02/02

  1. 1. MOBILE APPS CON OBJECTIVE-C DAY 02 19/NOVEMBRE/2011 alberto pasca | apasca@cutaway.it www.cutaway.i t
  2. 2. contents | day 02  interfacce grafiche  eventi  Foundation.framework  persistenza dati  librerie Mobile Apps con Objective-c | alberto pasca
  3. 3. interfacce grafiche (.xib) Mobile Apps con Objective-c | alberto pasca UIWindow UIView UIButton UILabel UITextField […] UIProgressBar
  4. 4. IBAction & IBOutlet Mobile Apps con Objective-c | alberto pasca @interface ViewController : UIViewController { IBOutletUIButton *FirstButton; } @property (nonatomic, retain) UIButton *FirstButton; - (IBAction) ButtonTouched:(id)sender; @end
  5. 5. controllers Mobile Apps con Objective-c | alberto pasca Navigation Controller Tab Bar Controller TableView Controller
  6. 6. Cosa vedremo… • IBAction • IBOutlet • UINavigationController • UITabBar • UITableView Lezione_05_controllers controllers – code Mobile Apps con Objective-c | alberto pasca
  7. 7. UIView – frame / bounds Mobile Apps con Objective-c | alberto pasca UIKit vs CoreGraphics
  8. 8. UIView - creazione Mobile Apps con Objective-c | alberto pasca UIView *v = [[UIViewalloc] initWithFrame:f]; [self.viewaddSubview:v]; [v release]; - (void)drawRect; v3 v2 v1 v4 •Aggiunte • Rimosse • Spostate di z-index • Trovate con i TAG • Animate • Riconoscono eventi muti-touch
  9. 9. UIView – gerarchia NSObject NSArray NSString UIResponder UIView UIControl UITextField UISlider UILabel Mobile Apps con Objective-c | alberto pasca
  10. 10. UIView – touch Mobile Apps con Objective-c | alberto pasca - (void) touchesBegan; - (void) touchesMoved; - (void) touchesEnded; - (void) touchesCancelled; Eventi touch generici Eventi touch particolari UITapGestureRecognizer UIPinchGestureRecognizer UIRotationGestureRecognizer UISwipeGestureRecognizer UIPanGestureRecognizer iOS 3.2+->UIGestureRecognizer iPad 11 dita insieme
  11. 11. UIView – animazioni Mobile Apps con Objective-c | alberto pasca { [UIViewbeginAnimations:@”MyAnimation"context:nil]; [UIViewsetAnimationDelegate:self]; [UIViewsetAnimationWillStartSelector:@selector(AnimStarted)]; [UIViewsetAnimationDidStopSelector:@selector(AnimStopped)]; [UIViewsetAnimationBeginsFromCurrentState:YES]; [UIViewsetAnimationDuration:2.0]; [...] [UIViewsetAnimationCurve:UIViewAnimationCurveEaseInOut]; MyView.alpha = .0; MyBeautifulButton.z = 100; // move // bounce // [...] [UIViewcommitAnimations]; }
  12. 12. Cosa vedremo… • UIView • Aggiunta / Rimozione • z-Index • Colori, dimensioni, etc… • Eventi Touch base • Eventi UIGestureResponder • Animazioni semplici Lezione_06_Animazioni Lezione_07_Touch touch e animazioni – code Mobile Apps con Objective-c | alberto pasca
  13. 13. UITableView Mobile Apps con Objective-c | alberto pasca • Data Source (Array) • Protocolli UITableViewDataSource UITableViewDelegate
  14. 14. UITableViewCell Mobile Apps con Objective-c | alberto pasca UITableViewCellStyleDefault UITableViewCellStyleSubtitle UITableViewCellStyleValue1 UITableViewCellStyleValue2
  15. 15. UIButton Mobile Apps con Objective-c | alberto pasca - (IBAction) ButtonTouched:(id)sender { UIButton *btn = (UIButton*)sender; switch (btn.tag) { // quale button? case0: break; case1: break; case2: break; // [...] } } TIPI CONFIG (UIButton*)sender
  16. 16. UITextField – UITextView Mobile Apps con Objective-c | alberto pasca Protocolli UITextFieldDelegate UITextViewDelegate • ShouldBeginEditing • DidBeginEditing • ShouldEndEditing • DidEndEditing • ShouldClear •ShouldReturn [textField becomeFirstResponder]; [textField resignFirstResponder];
  17. 17. UISwitch Mobile Apps con Objective-c | alberto pasca UISwitch *sw = [[UISwitchalloc] initWithFrame:CGRectMake(0, 0, 50, 100)]; sw.on = NO; sw.on = YES; X, Y, W, H CGRect rect; rect.origin.x = 0; rect.origin.y = 0; rect.size.width = 50; rect.size.height = 100;
  18. 18. UIImageView Mobile Apps con Objective-c | alberto pasca [ImgViewsetImage: [UIImageimageWithData: [NSDatadataWithContentsOfURL: [NSURLURLWithString: @"http://tinyurl.com/cr2tmu6" ] ] ] ];
  19. 19. UIWebBrowser Mobile Apps con Objective-c | alberto pasca Protocollo UIWebViewDelegate webViewDidStartLoad webViewDidFinishLoad didFailLoadWithError shouldStartLoadWithRequest [WebViewloadRequest: [NSURLRequestrequestWithURL: [NSURLURLWithString: textField.text]]]; [[UIApplicationsharedApplication] setNetworkActivityIndicatorVisible:YES];
  20. 20. Cosa vedremo… • UITextField • UITextView • UILabel • UIButton • UISwitch • UISlider • UIImageView • UIWebBrowser • Interazione codice Lezione_08_Componenti componenti – code Mobile Apps con Objective-c | alberto pasca
  21. 21. eventi Mobile Apps con Objective-c | alberto pasca
  22. 22. eventi - NSNotification Mobile Apps con Objective-c | alberto pasca creazione [[NSNotificationCenterdefaultCenter] addObserver:self selector:@selector(receiveTestNotification:) name:@"completato” object:nil]; [[NSNotificationCenterdefaultCenter] postNotificationName:@”completato"object:nil]; utilizzo [[NSNotificationCenterdefaultCenter] removeObserver:self]; distruzion e
  23. 23. eventi - gps  CoreLocation (CL) Framework  Protocollo <CLLocationManagerDelegate> - didUpdateToLocation - didFailWithError  [[CLLocationManager alloc]init]; CLLocationCoordinate2D coords = CLLocationCoordinate2DMake(45.50316, 9.16447); Mobile Apps con Objective-c | alberto pasca
  24. 24. Cosa vedremo… • Posizione GPS • Bussola Lezione_09_GPS gps / bussola – code Mobile Apps con Objective-c | alberto pasca
  25. 25. eventi - accelerometro Mobile Apps con Objective-c | alberto pasca  CoreLocation (CL) Framework  Protocollo <UIAccelerometerDelegate> - didAccelerate UIAcceleration: x, y, z [[UIAccelerometer sharedAccelerometer] setUpdateInterval:.2]; [[UIAccelerometer sharedAccelerometer] setDelegate:self];
  26. 26. eventi - rotazione - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation { // UIInterfaceOrientationPortrait // UIInterfaceOrientationLandscapeLeft // UIInterfaceOrientationLandscapeRight // UIInterfaceOrientationPortraitUpsideDown } Mobile Apps con Objective-c | alberto pasca
  27. 27. eventi - UIApplicationDelegate Mobile Apps con Objective-c | alberto pasca <UIApplicationDelegate > •didFinishLaunchingWithOptions Cambiamenti di stato • Da attivo a inattivo applicationWillResignActive • Da attivo a background applicationDidEnterBackground • Da background a inattivo applicationWillEnterForeground • Da inattivo ad attivo applicationDidBecomeActive • Da attivo a “sta per terminare” applicationWillTerminate Chiamata / SMS Quit REopen Sveglia Quit
  28. 28. Cosa vedremo… • UIApplicationDelegate • Giroscopio • Accelerometro • Device Motion • Magnetometro • Shake Lezione_10_Accelerometro movimenti – code Mobile Apps con Objective-c | alberto pasca
  29. 29. FoundationFramework Mobile Apps con Objective-c | alberto pasca
  30. 30. Foundation – NSString vs NSMutableString  Lunghezza: length  Ricerca: rangeOfString  Sostituzione: replaceCharactersInRange:withString  Inserimento caratteri: insertString:atIndex:  Comparazione: isEqualToString  Prefissi / Suffissi: hasPrefix, hasSuffix  Conversioni: intValue, doubleValue, UTF8String NSRange, NSMakeRange,NSNotFound Mobile Apps con Objective-c | alberto pasca
  31. 31. Foundation - NSNumber Mobile Apps con Objective-c | alberto pasca char, short int, int, long int, long long int, float, double, BOOL Utilizzare tipi scalari come oggetti + numberWithBool: + numberWithChar: + numberWithDouble: + numberWithFloat: + numberWithInt: + numberWithInteger: + numberWithLong: + numberWithLongLong: + numberWithShort: + numberWithUnsignedChar: + numberWithUnsignedInt: + numberWithUnsignedInteger: + numberWithUnsignedLong: + numberWithUnsignedLongLong: + numberWithUnsignedShort: – boolValue – charValue – decimalValue – doubleValue – floatValue – intValue – integerValue – longLongValue – longValue – shortValue – unsignedCharValue – unsignedIntegerValue – unsignedIntValue – unsignedLongLongValue – unsignedLongValue – unsignedShortValue ACCESSOCREAZIONE
  32. 32. Foundation - NSArray  elementi SOLO alla creazione  sola lettura  elementi in creazione  elementi in esecuzione  lettura / scrittura  shift automatico elementi NSArray NSMutableArray Mobile Apps con Objective-c | alberto pasca NSArray *nomeArray = [NSArrayarrayWithObjects:@"A",@"B",@"C",nil]; NSMutableArray *nomeMutableArray = [NSMutableArrayarrayWithObjects:@"A",@"B",@"C",nil]; [nomeMutableArray addObject:@"D"]; [nomeMutableArray insertObject:@"Z"atIndex:0]; NSLog(@"%@", [nomeArray objectAtIndex:0]); NSLog(@"%@", [nomeMutableArray objectAtIndex:0]);
  33. 33. Foundation - NSDictionary Mobile Apps con Objective-c | alberto pasca  elementi SOLO alla creazione  sola lettura  elementi in creazione  elementi in esecuzione  lettura / scrittura NSDictionary NSMutableDictionary NSDictionary *dict = [NSDictionarydictionaryWithObjectsAndKeys: @"VAL_00", @"KEY_00", @"VAL_01", @"KEY_01", nil]; NSMutableDictionary *mutDict = [NSMutableDictionarydictionaryWithObjectsAndKeys: @"VAL_00", @"KEY_00", @"VAL_01", @"KEY_01", nil]; [mutDict setValue:@"VAL_99"forKey:@"KEY_00"]; [mutDict setObject:@"VAL_02"forKey:@"KEY_02"]; NSLog(@"%@", [dict objectForKey:@"KEY_00"]); // valueForKey NSLog(@"%@", [mutDict objectForKey:@"KEY_00"]); // valueForKey
  34. 34. Cosa vedremo… • NSString • NSMutableString • NSNumber • NSArray • NSMutableArray • NSDictionary • NSMutableDictionary Lezione_11_Foundation Foundation.framework – code Mobile Apps con Objective-c | alberto pasca
  35. 35. persistenza dati Mobile Apps con Objective-c | alberto pasca
  36. 36. persistenza – NSUserDefault  “database” locale (area riservata)  thread safe NSString *sessionKey = @"865eft8itg98sdf3”; NSUserDefaults *store = [NSUserDefaultsstandardUserDefaults]; [store setObject:sessionKey forKey:@"SESSION"]; NSUserDefaults *get = [NSUserDefaultsstandardUserDefaults]; NSString *data = [get stringForKey:@"SESSION"]; NSLog(@"DATA: %@", data); Mobile Apps con Objective-c | alberto pasca
  37. 37. persistenza – NSCoding  store in locale di CLASSI intere <NSCoding> codifica / decodifica oggetti per l’archiviazione Mobile Apps con Objective-c | alberto pasca - (id) initWithCoder: (NSCoder *)decoder - (void) encodeWithCoder: (NSCoder *)coder Recupero oggetti/valore:decoder -> decodeObjectForKey Salvataggio oggetti/valore: coder -> encodeObject
  38. 38. persistenza – .plist e .bundle  NSBundle [[NSBundlemainBundle] pathForResource:@"Test”ofType:@"plist"]; == Test.plist <?xml version="1.0" encoding="UTF-8"?> <plist version="1.0"> <dict> <key>primo</key> <string>001</string> <key>secondo</key> <string>Valore 2</string> </dict> </plist> Mobile Apps con Objective-c | alberto pasca
  39. 39. persistenza – Root.plist  Accesso ai SETTINGS del device  Lettura / Scrittura con APP chiusa! Mobile Apps con Objective-c | alberto pasca
  40. 40. persistenza – SQLLite  Libreria libsqlite3.dylib  Funzionalità SQL, ma limitate  SELECT  INSERT  DELETE  etc…  Libreria in C, metodi in C  Editor come Terminale, Browser Plugin, IDE multipiattaforma Mobile Apps con Objective-c | alberto pasca
  41. 41. Cosa vedremo… • NSUserDefault • NSCoding • File .PLIST • Setting sistema • Conta esecuzioni app • Read/Write Settings • Salvataggio classi su store Lezione_12_Storage persistenza – code Mobile Apps con Objective-c | alberto pasca
  42. 42. librerie & extras Mobile Apps con Objective-c | alberto pasca
  43. 43. MKMapKit MKMapKit.framework  Mappe  Foto  Ibride  MKAnnotation  Localizzazione GPS  Polyline (no route!)  Geocodifica Mobile Apps con Objective-c | alberto pasca
  44. 44. Network  NSURL  NSURLRequest  NSURLConnection [[NSURLConnectionalloc] initWithRequest:request delegate:self] connectionDidFinishLoading connection didReceiveResponse connection didReceiveData connection didFailWithError Mobile Apps con Objective-c | alberto pasca
  45. 45. NSXMLParser <NSXMLParserDelegate>  Parsing XML  Carattere per carattere!  Callback per ogni evento – parserDidStartDocument: –parserDidEndDocument: – parser:parseErrorOccurred: – parser:foundCharacters: Mobile Apps con Objective-c | alberto pasca PRO: 1. Integrato 2. Velocissimo CONTRO: 1. Complesso 2. No XPATH !
  46. 46. librerie – TBXML / XPathQuery  OpenSource TBXML  Più veloce dopo NSXMLParser  Accesso diretto ai nodi e attributi XPathQuery (richiede la lib “libxml2.dlyb”)  Navigazione con Xpath  Recupero di tutti i nodi in un colpo solo Mobile Apps con Objective-c | alberto pasca http://goo.gl/Kr1Hk | http://goo.gl/Au6SV
  47. 47. librerie - FMDB  Wrapper per SQLLite  Scritto in Objective-C anziché in C  Molto facile da usare [FMDatabasedatabaseWithPath:dbPath] FMResultSet *rs = [dbexecuteQuery: @"SELECT / INSERT / etc…"]; [rs close]; Mobile Apps con Objective-c | alberto pasca http://goo.gl/szY0t
  48. 48. extras – device info Mobile Apps con Objective-c | alberto pasca  [[UIScreenmainScreen] bounds]  [UIScreenmainScreen].brightness  [UIDevicecurrentDevice].model  [UIDevicecurrentDevice].systemName  [UIDevicecurrentDevice].systemVersion  [UIDevicecurrentDevice].proximityMonitoringEnabled  [UIDevicecurrentDevice].uniqueIdentifier  [UIDevicecurrentDevice].orientation  [UIDevicecurrentDevice].multitaskingSupported  [UIDevicecurrentDevice].batteryLevel Schermo Device
  49. 49. extras – Paint !  CoreGraphics.framework > UIGraphicsBeginImageContext > UIGraphicsEndImageContext  CGContextSetLineWidth  CGContextSetRGBStrokeColor  CGContextAddLineToPoint Mobile Apps con Objective-c | alberto pasca
  50. 50. extras – Musica ! #import <AVFoundation/AVFoundation.h> #import <AudioToolbox/AudioToolbox.h> <AVAudioPlayerDelegate> [AVAudioPlayerinitWithContentsOfURL:url error:nil]; AudioPlayer.numberOfLoops = 0; [AudioPlayerplay]; [AudioPlayerstop]; AudioServicesPlaySystemSound(kSystemSoundID_Vibrate); Mobile Apps con Objective-c | alberto pasca Audio Vibrazion e
  51. 51. Cosa vedremo… • MKMapKit • Localizzazione GPS • MKAnnotation • MKMapType • Connessione HTTP • Syncronous / Asyncronous • NSXmlParser • TBXML • XPathQuery • Disegnare con le dita Lezione_13_MapKit Lezione_14_Network Lezione_15_XMLParser Lezione_16_Paint extras – code Mobile Apps con Objective-c | alberto pasca
  52. 52. # EOF - day 02. alberto pasca – apasca@cutaway.it Codice e slide verranno inviate ai partecipanti. grazie dell’attenzione.

×