ios7 - multitasking e dynamics - daniele galiotto
TRANSCRIPT
Multitasking & dynamic: le novità di iOS7 per il
multitasking e l'interazione tra le view
iOS7Multitaskin
gDynamics
iOS7
• Nuova grafica
• Nuove API
• XCode 5
• 64 Bit support
• Sprite Kit
• AirDrop
• Peer-to-Peer
• BLE
• Multitasking
• Dynamic
Multitasking
Fino a ieri• Background task
completion
• Background audio
• Location services
• VoIP
• Newsstand
iOS7 - Multitasking
• Background fetch
• Silent notifications
• Background transfer service
Background fetch• Basta attese di download
nuovi dati (o quasi)
• Download nuovi dati in background (UP -> DL -> BG)
• iOS7 impara quando effettuare un fetch
• Utile per app di news, social networks, meteo, photo sharing
Background fetch - Step one
• Abilitare background fetch (direttamente da XCode 5, Progetto/Capabilities)
Background fetch - Step one
• E’ importante abilitare solo ciò che serve,
• Apple non accetta app con opzioni inutilizzate
Background fetch - Step two
• Impostare l’intervallo di fetch nell’AppDelegate in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
• Di default è UIApplicationBackgroundFetchIntervalNever
• [application setMinimumBackgroundFetchInterval:UIApplicationBackgroundFetchIntervalMinimum];
Background fetch - Step two
• UIApplicationBackgroundFetchIntervalMinimum
• NSTimerInterval
Background fetch - Step three
• Implementare nell’AppDelegate il metodo application:performFetchWithCompletionHandler:
• UIBackgroundFetchResultNewData: se ci sono
nuovi dati, ricordarsi di aggiornare la UI
• UIBackgroundFetchResultNoData: se non ci sono nuovi dati
• UIBackgroundFetchResultFailed: se si è avuto un errore
Background fetch - Step three• Una richiesta fetch non può durare più
di 30 secondi fino al completionHandler altrimenti time out della richiesta
• Non abusarne, scaricare solo piccoli dati
Quando una fetch è quasi conclusa:
• Incrementare il badge/usare notifiche locali
• Richiamare il completionHandler
Background fetch - Debug
• Simulare il background fetch
• Abilitare l’opzione “Launch due to a background fetch event” (nello schema della app)
[DEMO]
Silent notifications• Sono notifiche… silenziose!
• Permettono di avviare un download di un nuovo contenuto non troppo corposo
• Il sistema sveglia la app (se necessario), processa la notifica (avvia il download) ed infine sta a noi notificare l’utente.
Silent notifications - Step one
• Abilitare remote notifications (direttamente da XCode 5, Progetto/Capabilities)
Silent notifications - Step one
• E’ importante abilitare solo ciò che serve,
• Apple non accetta app con opzioni inutilizzate
• Come per le push notification, vanno registrate le notifiche nell’AppDelegate in - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
• [application registerForRemoteNotificationTypes:UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound];
Silent notifications - Step two
• Implementare nell’AppDelegate il metodo application:didReceiveRemoteNotification:fetchCompletionHandler:
• UIBackgroundFetchResultNewData: se ci sono
nuovi dati, ricordarsi di aggiornare la UI
• UIBackgroundFetchResultNoData: se non ci sono nuovi dati
• UIBackgroundFetchResultFailed: se si è avuto un errore
Silent notifications - Step two
• Una push notification o silent notification, è un JSON
• Una silent notification è una push notification con contenuto:
content-available : 1
Silent notifications - Step three
{ "aps" : { "alert" : "YAP", "badge" : 2, "sound" : "sound.aiff" }}
{ "aps" : {
"content-available": 1, "sound": ""
}}
Silent notifications - Step three
• Una richiesta fetch non può durare più di 30 secondi fino al completionHandler altrimenti time out della richiesta
• Non abusarne, scaricare solo piccoli dati
• Non sempre sono consegnate appena inviate
• Troppe silent notification sono messe in coda e consegnate insieme
• Una push notification può essere anche una silent notification? Sì, purché abbia content-available = 1
Silent notifications - Step three
Quando una silent notification è quasi conclusa:
•Incrementare il badge/usare notifiche locali
•Richiamare il completionHandler
Silent notifications - Step three
• Inviare una silent notification tramite servizi tipo Parse.
Ovviamente prima si devono configurare Parse e la app per poter attivare le push notification.
Silent notifications - Debug
[DEMO]
Background transfer service
• Permette di trasferire grossi file
• Niente limite dei 10min come in iOS6
• iOS sveglia la app per gestire i trasferimenti.
Background transfer service
• I trasferimenti continuano anche se viene messa la app in background
• La app include una “Progress View”
• E’ basato sulla classe NSURLSession (iOS7)Questa classe trasferisce dati via HTTP o HTTPS
• Una sessione gestisce tutti i tasks relativi ai trasferimenti di dati.
NSURLSession - benefits
• Upload e download su thread in background
• Possibilità di mettere in pausa, stoppare e far ripartire un session task
• Configurazione unica per la sessione (NSURLSessionConfiguration)
• Gestione della autenticazione in base alla specifica connessione
NSURLSession - Step one
• NSURLSessionTask è la classe base per i task nella session
NSURLSession• NSURLSessionTask è la classe base per i
task nella session
• NSURLSessionDataTask: GET HTTP => NSData
• NSURLSessionUploadTask: NSData/File Stream => POST/PUT HTTP
• NSURLSessionDownloadTask:leggermente diversa dalle precedenti
NSURLSessionDownloadTask
• Task che lavora direttamente su file temp
• Durante il download viene aggiornato lo stato del trasferimento (progress view)
• Al termine del download è possibile salvare il file temp in una location permanente
• Supporta il resume del download
NSURLSessionDownloadTask - Step one
• Definire NSURLSessionConfiguration
=> defaultSessionConfiguration
• Definire NSURLSession
• Definire NSURLSessionDownloadTask (dall’istanza della session)
• Implementare il protocollo (interfaccia) desiderato
NSURLSessionDownloadTask - Step two
• I protocolli per le NSURLSession implementano il protocollo NSURLSessionDelegate
• NSURLSessionDownloadDelegate è il protocollo che utilizziamo
• NSURLSessionDownloadDelegate ha tre metodi @required (obbligatori)
NSURLSessionDownloadTask - Step two
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{}
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{}
[DEMO]
Background transfer service - Step one (come prima)
• Definire NSURLSessionConfiguration
=> backgroundSessionConfiguration (con ID univoco)
• Definire NSURLSession (usando il singleton)
• Definire NSURLSessionDownloadTask (dall’istanza della session)
• Implementare il protocollo (interfaccia) desiderato
Background transfer service - Step two (come prima)
• I protocolli per le NSURLSession implementano il protocollo NSURLSessionDelegate
• NSURLSessionDownloadDelegate è il protocollo che utilizziamo
• NSURLSessionDownloadDelegate ha tre metodi @required (obbligatori)
Background transfer service - Step three
• Implementare il metodo(void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
• Se l’app non è in foreground, sveglia l’app e comunica il termine degli eventi in background per una determinata session, avvisando l’AppDelegate
Background transfer service - Step three
• Nell’AppDelegate implementare il metodo-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler
• Metodo chiamato quando tutti i trasferimenti di background, associati ad una NSURLSession, sono completati o falliti. Viene chiamato prima del NSURLSession delegate.
Background transfer service - Step three
• Nell’AppDelegate implementare la property@property (copy) void (^backgroundSessionCompletionHandler)();
• È l’handler delle BackgroundURLSession, necessario per richiamare l’NSURLSessionDelegate
Background transfer service - Step four
• Avvisare l’utente con un badge o con una local notification
[DEMO]
Dynamics
iOS7 - Dynamic• Apple incoraggia la costruzione
di UI che permettano di percepire la realtà
• Non è necessario conoscere OpenGL
• g = 9,8ms2
• dist_oggetto = 0.5 x g x tempo^2
Dynamic - Nuovi tools
• UIKit Dynamics: motore fisico integrato in UIKit. Gestisce gravità, elasticità e forze.
• Motion Effects: permette di realizzare effetti di parallasse, legati al movimento del device
UIKit Dynamics
• UIDynamicAnimator è il motore fisico di UIKit, tiene traccia dei comportamenti aggiunti al motore
• Come riferimento ha una UIView (di solito self.view) che sfrutta per definire il proprio sistema di coordinate
UIKit Dynamics
• La formula per la distanza degli oggetti resta la stessa dist_oggetto = 0.5 x g x tempo^2
• Però, anziché lavorare con i metri, UIKit Dynamics lavora con le migliaia di pixel (per secondo quadrato)
UIKit Dynamics• UIGravityBehavior modella il
comportamento della gravità su uno o più item
• Ad esso è associato un insieme di item (UIView) influenzati da questo comportamento
• Proprietà gravitazionali: contiene proprietà che influenzano la forza di gravità (es. magnitude)
UIKit Dynamics
UIDynamicAnimator *animator = [[UIDynamicAnimator alloc] initWithReferenceView:self.view];
UIGravityBehavior *gravity = [[UIGravityBehavior alloc] initWithItems:@[myUIView]];
[animator addBehavior:gravity];
UIKit Dynamics•UICollisionBehavior definisce uno o più confini per la collisione
UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.theBomb]];
collision.translatesReferenceBoundsIntoBoundary = YES;
[animator addBehavior:collision];
UIKit Dynamics•UICollisionBehavior definisce uno o più confini per la collisione
UICollisionBehavior *collision = [[UICollisionBehavior alloc] initWithItems:@[self.theBomb, self.theTank]];
collision.translatesReferenceBoundsIntoBoundary = YES;
[animator addBehavior:collision];
UIKit Dynamics
CGPoint rightEdge = CGPointMake(self.theWall.frame.origin.x + self.theWall.frame.size.width, self.theWall.frame.origin.y);
[collision addBoundaryWithIdentifier:@"wall" fromPoint:self.theWall.frame.origin toPoint:rightEdge];
UIKit Dynamics
•UIDynamicBehavior per configurare le proprietà degli item
elasticity, friction, density, resistance, angularResistance, allowsRotation
[DEMO]
Avanti il prossimo!
Tiziano Cacioppolini
WP8 Developer
Storage su WP8