SlideShare una empresa de Scribd logo
1 de 49
Descargar para leer sin conexión
sabato 26 ottobre 13
What’s new? Multitasking
API on iOS 7
Francesco Novelli
iOS and Web Developer Freelance
@if9
francesco.nove@gmail.com
sabato 26 ottobre 13
Novità per l’utente

‣Nuova grafica
‣Nuove impostazioni
‣Resta tutto trasparente

sabato 26 ottobre 13
Grafica iOS 6 vs. iOS 7

sabato 26 ottobre 13
Le nuove impostazioni

sabato 26 ottobre 13
Per noi, fan di
#pragma mark
sabato 26 ottobre 13
Modalità di Background fino a iOS 6
‣Background Task Completion
‣Background Audio
‣Location Services
‣VoIP
‣Newsstand

sabato 26 ottobre 13
Novità di iOS 7

‣Background Fetch
‣Silent Notifications
‣Background Transfer Service
‣Bluetooth LE

sabato 26 ottobre 13
Impostazioni in Xcode 5

sabato 26 ottobre 13
ATTENZIONE!

Inserire SOLO le opzioni che vengono utilizzate
nell’app
Apple boccia le app che hanno opzioni inutilizzate!

sabato 26 ottobre 13
Background Fetch

‣Registrare l’app per richiederlo
‣Impostare quanto spesso
‣Il resto... ci pensa iOS (più o meno)

sabato 26 ottobre 13
Background Fetch

iOS registra l’attività degli utenti, capendo quanto e
quando un utente usa l’app
Usando tutti i giorni un pattern di apertura app, iOS
IMPARA

sabato 26 ottobre 13
Day 1
9:15 AM

Day 2
9:15 AM

9:30 AM

Day n
9:15 AM

10:00 AM

10:30 AM

10:30 AM

1:00 PM

1:00 PM

1:00 PM
1:15 PM

3:00 PM

3:00 PM

5:00 PM

5:00 PM

5:00 PM

5:15 PM

5:15 PM

5:15 PM

sabato 26 ottobre 13

Device observes
the pattern
Quando usarlo
‣Social Networks apps
‣News Apps
‣Contenuto aggiornato spesso
‣Applicazione consultata spesso
‣Contenuto di poco peso

sabato 26 ottobre 13
Come implementarlo
Registrare nel plist (o impostazioni app)
UIBackgroundModes: fetch

sabato 26 ottobre 13
Come implementarlo
Impostare il fetching time
[app setMinimumBackgroundFetchInterval:
UIApplicationBackgroundFetchIntervalMinimum]
Opzioni:
•UIApplicationBackgroundFetchIntervalMinimum
•UIApplicationBackgroundFetchIntervalNever
(default)

sabato 26 ottobre 13
Come implementarlo
Metodo del delegate richiamata:
- (void)application:(UIApplication *)application
performFetchWithCompletionHandler:
(void (^)(UIBackgroundFetchResult result))
completionHandler;
UIApplicationDelegate, da implementare (solitamente)
nel file AppDelegate.m

sabato 26 ottobre 13
Come implementarlo
Eseguire il codice all’interno del metodo del delegate:
Alla fine dell’esecuzione:
- incrementare l’app badge
- richiamare il completition handler

se c’è nuovo contenuto:
UIBackgroundFetchResultNewData
se non c’è nuovo contenuto:
UIBackgroundFetchResultNoData
se c’è stato errore:
UIBackgroundFetchResultFailed

sabato 26 ottobre 13
Testare il fetching
Attivare nello Schema di Debug

sabato 26 ottobre 13
Testare il fetching
Simulare il background fetch

sabato 26 ottobre 13
Consigli
- Non fare affidamento SOLO sul fetch
- Scaricare meno dati possibili
- Non scaricare video, foto o contenuti multimediali
- Ricaricare le view, così da aggiornare l’anteprima
- Aggiornare il badge
- Usare le Notifiche locali

sabato 26 ottobre 13
NeXT...
sabato 26 ottobre 13
Cosa conosciamo e usiamo sempre?
- Notifiche Push
- Notifiche locali
Il nuovo arrivato?

Silent Notification

sabato 26 ottobre 13
Silent Notification
- Funzionano via web
- Certificati per notifiche push
- Sono notifiche push! Identiche, ma...

Non “suonano”
invsibili per l’utente

sabato 26 ottobre 13
Silent Notification

- Permettono di “svegliare” l’app
- Nuovo metodo dell’AppDelegate
- Possibile eseguire codice

sabato 26 ottobre 13
Quando usarlo

- Aggiornamenti sporadici
- Aggiornamenti corposi (video, podcast, etc)
- Sincronizzare contenuti

sabato 26 ottobre 13
Come implementarlo
Registrare nel plist (o impostazioni app)
UIBackgroundModes: remote-notification

sabato 26 ottobre 13
Come implementarlo
Registrare le notifiche (come per le push):
[application registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeAlert |
UIRemoteNotificationTypeSound)];

sabato 26 ottobre 13
Come implementarlo
Metodo del delegate richiamata:
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary
*)userInfo
fetchCompletionHandler:
(void (^)
(UIBackgroundFetchResult))completionHandler;
UIApplicationDelegate, da implementare (solitamente)
nel file AppDelegate.m

sabato 26 ottobre 13
Come implementarlo
Eseguire il codice all’interno del metodo del delegate:
Alla fine dell’esecuzione:
- incrementare l’app badge
- richiamare il completition handler

se c’è nuovo contenuto:
UIBackgroundFetchResultNewData
se non c’è nuovo contenuto:
UIBackgroundFetchResultNoData
se c’è stato errore:
UIBackgroundFetchResultFailed

sabato 26 ottobre 13
Com’è fatta una notifica
Payload notifiche push:
{
"aps": {
"alert": "Ufficiale: Messi al Milan",
"sound": "default" }
}

Payload silent notification:
{
"aps": {
"content-available": 1 }
}
sabato 26 ottobre 13
Consigli
- Non esagerare
- Non sempre consegnate appena inviate
- Troppe silent notification vengono messe in coda e
consegnate insieme
- Le notifiche push normali possono avere l’attributo
content-available e richiamare il codice

sabato 26 ottobre 13
Last but
not least...
sabato 26 ottobre 13
Background
Transfer
Service
sabato 26 ottobre 13
Background Transfer Service
- In iOS 6 solo qualche minuto per i download (10
minuti)
- Non ha bisogno di autorizzazioni utente
- Permette di scaricare grossi file
- Notifiche per gestire errori
- Tutto gestito da iOS! Trasparente per i dev e gli
utenti

sabato 26 ottobre 13
Background Transfer Service

Come implementarlo?
Usando NSURLSession e NSURLSessionDownloadTask

sabato 26 ottobre 13
Background Transfer Service
if (!self.urlSession) {
NSString* sessionID = @"ajeje123";
NSURLSessionConfiguration* config = [NSURLSessionConfiguration
backgroundSessionConfiguration:sessionID];
self.urlSession = [NSURLSession sessionWithConfiguration:config
delegate:self
delegateQueue:[NSOperationQueue mainQueue]];
}
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:@"http://www.auby.no/files/video_tests/
h264_720p_hp_5.1_6mbps_ac3_planet.mp4"]];
self.downloadTask = [self.urlSession downloadTaskWithRequest:request];
[self.downloadTask resume];

sabato 26 ottobre 13
NSURLSessionDownloadTask
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
dispatch_async(dispatch_get_main_queue(), ^{
self.downloadProgress.progress = (double)totalBytesWritten /
(double)totalBytesExpectedToWrite;
});
}

sabato 26 ottobre 13
NSURLSessionDownloadTask
- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)downloadURL {
NSString* lastPathComponent = [downloadTask.originalRequest.URL
lastPathComponent];
NSString* destinationPath = [[self docPath]
stringByAppendingPathComponent:lastPathComponent];
NSURL* destinationURL = [NSURL fileURLWithPath:destinationPath];
NSError* error;
BOOL copySuccessful = [[NSFileManager defaultManager] copyItemAtURL:downloadURL
toURL:destinationURL error:&error];
dispatch_async(dispatch_get_main_queue(), ^{
self.downloadProgress.hidden = YES;
});
}

sabato 26 ottobre 13
NSURLSessionDownloadTask

- (void)URLSession:(NSURLSession *)session
downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes {
}

sabato 26 ottobre 13
NSURLSessionTaskDelegate

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(NSError *)error {
if (error) {
NSString* lastPathComponent = [task.originalRequest.URL lastPathComponent];
NSString* filePath = [[self docPath]
stringByAppendingPathComponent:lastPathComponent];
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
}
}

sabato 26 ottobre 13
Notifiche (AppDelegate)
- (void)application:(UIApplication *)application
handleEventsForBackgroundURLSession:(NSString *)identifier
completionHandler:(void (^)())completionHandler {
NSDictionary* userInfo = @{@"completionHandler" : completionHandler,
@"sessID" : identifier};
[[NSNotificationCenter defaultCenter] postNotificationName:@"BgNotification"
object:nil userInfo:userInfo];
}

sabato 26 ottobre 13
Registrare la notifica

[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(handleBackgroundTransfer:)
name:@"BgNotification"
object:nil];

sabato 26 ottobre 13
Gestire il background

- (void)handleBackgroundTransfer:(NSNotification*)notification {
dispatch_async(dispatch_get_main_queue(), ^{
self.downloadProgress.hidden = YES;
void(^completionHandler)(void) = notification.userInfo[@"completionHandler"];
if (completionHandler) {
completionHandler();
}
});
}

sabato 26 ottobre 13
Consigli

- Eseguire SOLO i task necessari. Non aggiungere cose
inutili
- Non eseguire codice di OpenGL ES
- Usare il minor spazio di memoria possibile, altrimenti
iOS ci potrebbe killare
- Salvare lo stato dell’app, in caso fosse chiusa

sabato 26 ottobre 13
Background LE
Sessione
“Realizzare accessori iOS con Arduino e Bluetooth
4.0”.

Fiore Basile
Sala Craig Federighi.
14:15

sabato 26 ottobre 13
Novità di iOS 7
‣Background Fetch
‣Silent Notifications
‣Background Transfer Service

sabato 26 ottobre 13
Thanks!
Francesco Novelli
iOS and Web Developer Freelance
@if9
francesco.nove@gmail.com
sabato 26 ottobre 13
sabato 26 ottobre 13

Más contenido relacionado

Destacado

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destacado (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

What's New in Multitasking on iOS 7 [#PragmaConf 2013]

  • 2. What’s new? Multitasking API on iOS 7 Francesco Novelli iOS and Web Developer Freelance @if9 francesco.nove@gmail.com sabato 26 ottobre 13
  • 3. Novità per l’utente ‣Nuova grafica ‣Nuove impostazioni ‣Resta tutto trasparente sabato 26 ottobre 13
  • 4. Grafica iOS 6 vs. iOS 7 sabato 26 ottobre 13
  • 6. Per noi, fan di #pragma mark sabato 26 ottobre 13
  • 7. Modalità di Background fino a iOS 6 ‣Background Task Completion ‣Background Audio ‣Location Services ‣VoIP ‣Newsstand sabato 26 ottobre 13
  • 8. Novità di iOS 7 ‣Background Fetch ‣Silent Notifications ‣Background Transfer Service ‣Bluetooth LE sabato 26 ottobre 13
  • 9. Impostazioni in Xcode 5 sabato 26 ottobre 13
  • 10. ATTENZIONE! Inserire SOLO le opzioni che vengono utilizzate nell’app Apple boccia le app che hanno opzioni inutilizzate! sabato 26 ottobre 13
  • 11. Background Fetch ‣Registrare l’app per richiederlo ‣Impostare quanto spesso ‣Il resto... ci pensa iOS (più o meno) sabato 26 ottobre 13
  • 12. Background Fetch iOS registra l’attività degli utenti, capendo quanto e quando un utente usa l’app Usando tutti i giorni un pattern di apertura app, iOS IMPARA sabato 26 ottobre 13
  • 13. Day 1 9:15 AM Day 2 9:15 AM 9:30 AM Day n 9:15 AM 10:00 AM 10:30 AM 10:30 AM 1:00 PM 1:00 PM 1:00 PM 1:15 PM 3:00 PM 3:00 PM 5:00 PM 5:00 PM 5:00 PM 5:15 PM 5:15 PM 5:15 PM sabato 26 ottobre 13 Device observes the pattern
  • 14. Quando usarlo ‣Social Networks apps ‣News Apps ‣Contenuto aggiornato spesso ‣Applicazione consultata spesso ‣Contenuto di poco peso sabato 26 ottobre 13
  • 15. Come implementarlo Registrare nel plist (o impostazioni app) UIBackgroundModes: fetch sabato 26 ottobre 13
  • 16. Come implementarlo Impostare il fetching time [app setMinimumBackgroundFetchInterval: UIApplicationBackgroundFetchIntervalMinimum] Opzioni: •UIApplicationBackgroundFetchIntervalMinimum •UIApplicationBackgroundFetchIntervalNever (default) sabato 26 ottobre 13
  • 17. Come implementarlo Metodo del delegate richiamata: - (void)application:(UIApplication *)application performFetchWithCompletionHandler: (void (^)(UIBackgroundFetchResult result)) completionHandler; UIApplicationDelegate, da implementare (solitamente) nel file AppDelegate.m sabato 26 ottobre 13
  • 18. Come implementarlo Eseguire il codice all’interno del metodo del delegate: Alla fine dell’esecuzione: - incrementare l’app badge - richiamare il completition handler se c’è nuovo contenuto: UIBackgroundFetchResultNewData se non c’è nuovo contenuto: UIBackgroundFetchResultNoData se c’è stato errore: UIBackgroundFetchResultFailed sabato 26 ottobre 13
  • 19. Testare il fetching Attivare nello Schema di Debug sabato 26 ottobre 13
  • 20. Testare il fetching Simulare il background fetch sabato 26 ottobre 13
  • 21. Consigli - Non fare affidamento SOLO sul fetch - Scaricare meno dati possibili - Non scaricare video, foto o contenuti multimediali - Ricaricare le view, così da aggiornare l’anteprima - Aggiornare il badge - Usare le Notifiche locali sabato 26 ottobre 13
  • 23. Cosa conosciamo e usiamo sempre? - Notifiche Push - Notifiche locali Il nuovo arrivato? Silent Notification sabato 26 ottobre 13
  • 24. Silent Notification - Funzionano via web - Certificati per notifiche push - Sono notifiche push! Identiche, ma... Non “suonano” invsibili per l’utente sabato 26 ottobre 13
  • 25. Silent Notification - Permettono di “svegliare” l’app - Nuovo metodo dell’AppDelegate - Possibile eseguire codice sabato 26 ottobre 13
  • 26. Quando usarlo - Aggiornamenti sporadici - Aggiornamenti corposi (video, podcast, etc) - Sincronizzare contenuti sabato 26 ottobre 13
  • 27. Come implementarlo Registrare nel plist (o impostazioni app) UIBackgroundModes: remote-notification sabato 26 ottobre 13
  • 28. Come implementarlo Registrare le notifiche (come per le push): [application registerForRemoteNotificationTypes: (UIRemoteNotificationTypeBadge | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeSound)]; sabato 26 ottobre 13
  • 29. Come implementarlo Metodo del delegate richiamata: - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler: (void (^) (UIBackgroundFetchResult))completionHandler; UIApplicationDelegate, da implementare (solitamente) nel file AppDelegate.m sabato 26 ottobre 13
  • 30. Come implementarlo Eseguire il codice all’interno del metodo del delegate: Alla fine dell’esecuzione: - incrementare l’app badge - richiamare il completition handler se c’è nuovo contenuto: UIBackgroundFetchResultNewData se non c’è nuovo contenuto: UIBackgroundFetchResultNoData se c’è stato errore: UIBackgroundFetchResultFailed sabato 26 ottobre 13
  • 31. Com’è fatta una notifica Payload notifiche push: { "aps": { "alert": "Ufficiale: Messi al Milan", "sound": "default" } } Payload silent notification: { "aps": { "content-available": 1 } } sabato 26 ottobre 13
  • 32. Consigli - Non esagerare - Non sempre consegnate appena inviate - Troppe silent notification vengono messe in coda e consegnate insieme - Le notifiche push normali possono avere l’attributo content-available e richiamare il codice sabato 26 ottobre 13
  • 35. Background Transfer Service - In iOS 6 solo qualche minuto per i download (10 minuti) - Non ha bisogno di autorizzazioni utente - Permette di scaricare grossi file - Notifiche per gestire errori - Tutto gestito da iOS! Trasparente per i dev e gli utenti sabato 26 ottobre 13
  • 36. Background Transfer Service Come implementarlo? Usando NSURLSession e NSURLSessionDownloadTask sabato 26 ottobre 13
  • 37. Background Transfer Service if (!self.urlSession) { NSString* sessionID = @"ajeje123"; NSURLSessionConfiguration* config = [NSURLSessionConfiguration backgroundSessionConfiguration:sessionID]; self.urlSession = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]]; } NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.auby.no/files/video_tests/ h264_720p_hp_5.1_6mbps_ac3_planet.mp4"]]; self.downloadTask = [self.urlSession downloadTaskWithRequest:request]; [self.downloadTask resume]; sabato 26 ottobre 13
  • 38. NSURLSessionDownloadTask - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { dispatch_async(dispatch_get_main_queue(), ^{ self.downloadProgress.progress = (double)totalBytesWritten / (double)totalBytesExpectedToWrite; }); } sabato 26 ottobre 13
  • 39. NSURLSessionDownloadTask - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)downloadURL { NSString* lastPathComponent = [downloadTask.originalRequest.URL lastPathComponent]; NSString* destinationPath = [[self docPath] stringByAppendingPathComponent:lastPathComponent]; NSURL* destinationURL = [NSURL fileURLWithPath:destinationPath]; NSError* error; BOOL copySuccessful = [[NSFileManager defaultManager] copyItemAtURL:downloadURL toURL:destinationURL error:&error]; dispatch_async(dispatch_get_main_queue(), ^{ self.downloadProgress.hidden = YES; }); } sabato 26 ottobre 13
  • 40. NSURLSessionDownloadTask - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes { } sabato 26 ottobre 13
  • 41. NSURLSessionTaskDelegate - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { if (error) { NSString* lastPathComponent = [task.originalRequest.URL lastPathComponent]; NSString* filePath = [[self docPath] stringByAppendingPathComponent:lastPathComponent]; [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil]; } } sabato 26 ottobre 13
  • 42. Notifiche (AppDelegate) - (void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler { NSDictionary* userInfo = @{@"completionHandler" : completionHandler, @"sessID" : identifier}; [[NSNotificationCenter defaultCenter] postNotificationName:@"BgNotification" object:nil userInfo:userInfo]; } sabato 26 ottobre 13
  • 43. Registrare la notifica [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleBackgroundTransfer:) name:@"BgNotification" object:nil]; sabato 26 ottobre 13
  • 44. Gestire il background - (void)handleBackgroundTransfer:(NSNotification*)notification { dispatch_async(dispatch_get_main_queue(), ^{ self.downloadProgress.hidden = YES; void(^completionHandler)(void) = notification.userInfo[@"completionHandler"]; if (completionHandler) { completionHandler(); } }); } sabato 26 ottobre 13
  • 45. Consigli - Eseguire SOLO i task necessari. Non aggiungere cose inutili - Non eseguire codice di OpenGL ES - Usare il minor spazio di memoria possibile, altrimenti iOS ci potrebbe killare - Salvare lo stato dell’app, in caso fosse chiusa sabato 26 ottobre 13
  • 46. Background LE Sessione “Realizzare accessori iOS con Arduino e Bluetooth 4.0”. Fiore Basile Sala Craig Federighi. 14:15 sabato 26 ottobre 13
  • 47. Novità di iOS 7 ‣Background Fetch ‣Silent Notifications ‣Background Transfer Service sabato 26 ottobre 13
  • 48. Thanks! Francesco Novelli iOS and Web Developer Freelance @if9 francesco.nove@gmail.com sabato 26 ottobre 13