contents | day 02
interfacce grafiche eventi Foundation.framework persistenza dati librerie
Mobile Apps con Objective-c | alberto pasca
interfacce grafiche (.xib)Mobile Apps con Objective-c |
alberto pasca
UIWindow
UIView
UIButton
UILabel
UITextField
[…]
UIProgressBar
IBAction & IBOutletMobile Apps con Objective-c |
alberto pasca
@interface ViewController : UIViewController { IBOutlet UIButton *FirstButton;}
@property (nonatomic, retain) UIButton *FirstButton;
- (IBAction) ButtonTouched:(id)sender;
@end
controllersMobile Apps con Objective-c |
alberto pasca
NavigationController
Tab BarController
TableViewController
Cosa vedremo…
• IBAction• IBOutlet
• UINavigationController• UITabBar• UITableView
Lezione_05_controllers
controllers – codeMobile Apps con Objective-c |
alberto pasca
UIView – frame / boundsMobile Apps con Objective-c |
alberto pasca
UIKit vs CoreGraphics
UIView - creazioneMobile Apps con Objective-c |
alberto pasca
UIView *v = [[UIView alloc] initWithFrame:f];[self.view addSubview:v];[v release];
- (void)drawRect;
v3
v2 v1
v4
• Aggiunte• Rimosse• Spostate di z-index• Trovate con i TAG• Animate• Riconoscono eventi muti-touch
UIView – gerarchia
NSObject
NSArray NSString UIResponder
UIView
UIControl
UITextField UISlider
UILabel
Mobile Apps con Objective-c | alberto pasca
UIView – touchMobile Apps con Objective-c |
alberto pasca
- (void) touchesBegan;- (void) touchesMoved;- (void) touchesEnded;- (void) touchesCancelled;
Eventi touch generici
Eventi touch particolari
UITapGestureRecognizer
UIPinchGestureRecognizerUIRotationGestureRecognizer
UISwipeGestureRecognizerUIPanGestureRecognizer
UILongPressGestureRecognizer
iOS 3.2+ -> UIGestureRecognizer
iPad 11 dita insieme
UIView – animazioniMobile Apps con Objective-c |
alberto pasca
{[UIView beginAnimations:@”MyAnimation" context:nil];
[UIView setAnimationDelegate:self];[UIView setAnimationWillStartSelector:@selector(AnimStarted)];[UIView setAnimationDidStopSelector:@selector(AnimStopped)];
[UIView setAnimationBeginsFromCurrentState:YES];[UIView setAnimationDuration:2.0];[...][UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
MyView.alpha = .0;MyBeautifulButton.z = 100;// move// bounce// [...]
[UIView commitAnimations];}
Cosa vedremo…
• UIView• Aggiunta / Rimozione• z-Index• Colori, dimensioni,
etc…
• Eventi Touch base• Eventi
UIGestureResponder• Animazioni semplici
Lezione_06_AnimazioniLezione_07_Touch
touch e animazioni – codeMobile Apps con Objective-c |
alberto pasca
UITableViewMobile Apps con Objective-c |
alberto pasca
• Data Source (Array)
• ProtocolliUITableViewDataSource
UITableViewDelegate
UITableViewCellMobile Apps con Objective-c |
alberto pasca
UITableViewCellStyleDefault
UITableViewCellStyleSubtitle
UITableViewCellStyleValue1
UITableViewCellStyleValue2
UIButtonMobile Apps con Objective-c |
alberto pasca
- (IBAction) ButtonTouched:(id)sender { UIButton *btn = (UIButton*)sender; switch (btn.tag) { // quale button? case 0: break; case 1: break; case 2: break; // [...] }}
TIPI
CONFIG
(UIButton*)sender
UITextField – UITextViewMobile Apps con Objective-c |
alberto pasca
Protocolli UITextFieldDelegateUITextViewDelegate
• ShouldBeginEditing• DidBeginEditing• ShouldEndEditing• DidEndEditing• ShouldClear• ShouldReturn
[textField becomeFirstResponder];[textField resignFirstResponder];
UISwitchMobile Apps con Objective-c |
alberto pasca
UISwitch *sw = [[UISwitch alloc] 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;
UIImageViewMobile Apps con Objective-c |
alberto pasca
[ImgView setImage: [UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString: @"http://tinyurl.com/cr2tmu6" ] ] ] ];
UIWebBrowserMobile Apps con Objective-c |
alberto pasca
Protocollo UIWebViewDelegate
webViewDidStartLoadwebViewDidFinishLoaddidFailLoadWithErrorshouldStartLoadWithRequest
[WebView loadRequest: [NSURLRequest requestWithURL: [NSURL URLWithString: textField.text]]];
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
Cosa vedremo…
• UITextField• UITextView• UILabel• UIButton• UISwitch• UISlider• UIImageView• UIWebBrowser
• Interazione codice
Lezione_08_Componenti
componenti – codeMobile Apps con Objective-c |
alberto pasca
eventi
Mobile Apps con Objective-c | alberto pasca
eventi - NSNotificationMobile Apps con Objective-c |
alberto pasca
creazione[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveTestNotification:) name:@"completato” object:nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@”completato" object:nil];
utilizzo
[[NSNotificationCenter defaultCenter] removeObserver:self];
distruzione
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
Cosa vedremo…
• Posizione GPS• Bussola
Lezione_09_GPS
gps / bussola – codeMobile Apps con Objective-c |
alberto pasca
eventi - accelerometroMobile Apps con Objective-c |
alberto pasca
CoreLocation (CL) Framework Protocollo <UIAccelerometerDelegate>
- didAccelerate
UIAcceleration: x, y, z
[[UIAccelerometer sharedAccelerometer] setUpdateInterval:.2];
[[UIAccelerometer sharedAccelerometer] setDelegate:self];
eventi - rotazione
- (BOOL) shouldAutorotateToInterfaceOrientation:
(UIInterfaceOrientation)interfaceOrientation
{
// UIInterfaceOrientationPortrait
// UIInterfaceOrientationLandscapeLeft
// UIInterfaceOrientationLandscapeRight
// UIInterfaceOrientationPortraitUpsideDown
}
Mobile Apps con Objective-c | alberto pasca
eventi - UIApplicationDelegate
Mobile Apps con Objective-c | alberto pasca
< UIApplicationDelegate >
• didFinishLaunchingWithOptions
Cambiamenti di stato• Da attivo a inattivo
applicationWillResignActive
• Da attivo a backgroundapplicationDidEnterBackground
• Da background a inattivoapplicationWillEnterForeground
• Da inattivo ad attivoapplicationDidBecomeActive
• Da attivo a “sta per terminare”applicationWillTerminate
Chiamata / SMS
Quit
REopen
Sveglia
Quit
Cosa vedremo…
• UIApplicationDelegate• Giroscopio• Accelerometro• Device Motion• Magnetometro• Shake
Lezione_10_Accelerometro
movimenti – codeMobile Apps con Objective-c |
alberto pasca
FoundationFramework
Mobile Apps con Objective-c | alberto pasca
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
Foundation - NSNumberMobile 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
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 = [NSArray arrayWithObjects:@"A",@"B",@"C",nil];
NSMutableArray *nomeMutableArray = [NSMutableArray arrayWithObjects:@"A",@"B",@"C",nil]; [nomeMutableArray addObject:@"D"]; [nomeMutableArray insertObject:@"Z" atIndex:0]; NSLog(@"%@", [nomeArray objectAtIndex:0]); NSLog(@"%@", [nomeMutableArray objectAtIndex:0]);
Foundation - NSDictionaryMobile Apps con Objective-c |
alberto pasca
elementi SOLO alla creazione
sola lettura
elementi in creazione elementi in esecuzione lettura / scrittura
NSDictionary NSMutableDictionary
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys: @"VAL_00", @"KEY_00", @"VAL_01", @"KEY_01", nil]; NSMutableDictionary *mutDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
@"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"]); // valueForKeyNSLog(@"%@", [mutDict objectForKey:@"KEY_00"]); // valueForKey
Cosa vedremo…
• NSString• NSMutableString• NSNumber• NSArray• NSMutableArray• NSDictionary• NSMutableDictionary
Lezione_11_Foundation
Foundation.framework – code
Mobile Apps con Objective-c | alberto pasca
persistenza dati
Mobile Apps con Objective-c | alberto pasca
persistenza – NSUserDefault
“database” locale (area riservata) thread safe
NSString *sessionKey = @"865eft8itg98sdf3”;
NSUserDefaults *store = [NSUserDefaults standardUserDefaults];
[store setObject:sessionKey forKey:@"SESSION"];
NSUserDefaults *get = [NSUserDefaults standardUserDefaults];
NSString *data = [get stringForKey:@"SESSION"];
NSLog(@"DATA: %@", data);
Mobile Apps con Objective-c | alberto pasca
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 -> decodeObjectForKeySalvataggio oggetti/valore: coder -> encodeObject
persistenza – .plist e .bundle NSBundle
[[NSBundle mainBundle] 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
persistenza – Root.plist
Accesso ai SETTINGS del device Lettura / Scrittura con APP chiusa!
Mobile Apps con Objective-c | alberto pasca
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
Cosa vedremo…
• NSUserDefault• NSCoding• File .PLIST• Setting sistema
• Conta esecuzioni app• Read/Write Settings• Salvataggio classi su
store
Lezione_12_Storage
persistenza – codeMobile Apps con Objective-c |
alberto pasca
librerie & extras
Mobile Apps con Objective-c | alberto pasca
MKMapKit
MKMapKit.framework
Mappe Foto Ibride
MKAnnotation Localizzazione GPS Polyline (no route!) Geocodifica
Mobile Apps con Objective-c | alberto pasca
Network
NSURL NSURLRequest NSURLConnection
[[NSURLConnection alloc] initWithRequest:request delegate:self]
connectionDidFinishLoadingconnection didReceiveResponseconnection didReceiveDataconnection didFailWithError
Mobile Apps con Objective-c | alberto pasca
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. Integrato2. Velocissimo
CONTRO: 3. Complesso4. No XPATH !
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
librerie - FMDB
Wrapper per SQLLite Scritto in Objective-C anziché in C Molto facile da usare
[FMDatabase databaseWithPath:dbPath]
FMResultSet *rs = [db executeQuery:
@"SELECT / INSERT / etc…"];
[rs close];
Mobile Apps con Objective-c | alberto pasca
http://goo.gl/szY0t
extras – device infoMobile Apps con Objective-c |
alberto pasca
[[UIScreen mainScreen] bounds] [UIScreen mainScreen].brightness
[UIDevice currentDevice].model [UIDevice currentDevice].systemName [UIDevice currentDevice].systemVersion [UIDevice currentDevice].proximityMonitoringEnabled [UIDevice currentDevice].uniqueIdentifier [UIDevice currentDevice].orientation [UIDevice currentDevice].multitaskingSupported [UIDevice currentDevice].batteryLevel
Schermo
Device
extras – Paint !
CoreGraphics.framework
> UIGraphicsBeginImageContext
> UIGraphicsEndImageContext
CGContextSetLineWidth CGContextSetRGBStrokeColor CGContextAddLineToPoint
Mobile Apps con Objective-c | alberto pasca
extras – Musica !
#import <AVFoundation/AVFoundation.h>#import <AudioToolbox/AudioToolbox.h>
<AVAudioPlayerDelegate>
[AVAudioPlayer initWithContentsOfURL:url error:nil];AudioPlayer.numberOfLoops = 0;[AudioPlayer play];[AudioPlayer stop];
AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
Mobile Apps con Objective-c | alberto pasca
Audio
Vibrazione
Cosa vedremo…
• MKMapKit• Localizzazione GPS• MKAnnotation• MKMapType
• Connessione HTTP• Syncronous /
Asyncronous
• NSXmlParser• TBXML• XPathQuery
• Disegnare con le dita
Lezione_13_MapKitLezione_14_NetworkLezione_15_XMLParserLezione_16_Paint
extras – codeMobile Apps con Objective-c |
alberto pasca
# EOF - day 02.
alberto pasca – [email protected]
Codice e slide verranno inviate ai partecipanti.
grazie dell’attenzione.