SlideShare a Scribd company logo
iOS Networking:
                          Bonjour, iCloud!
                          Chris Adamson • @invalidname
                                 CodeMash 2012




Monday, January 16, 12
What we’ll cover

                    • Obvious networking APIs
                     • iCloud, Bonjour, GameKit, CFNetwork
                    • Not-so-obvious networking APIs
                     • Foundation, media APIs, System
                         Configuration



Monday, January 16, 12
The first thing your
                         network app should
                                do?


Monday, January 16, 12
Monday, January 16, 12
Do I have network
                           access at all?


Monday, January 16, 12
Reachability

                    • Defined in SystemConfiguration.framework
                    • C-based API, Obj-C wrapper available as
                         sample code from Apple
                    • Your network-based app will be
                         rejected if it turtles without network
                         access



Monday, January 16, 12
Monday, January 16, 12
Reachability

                    • Create a SCNetworkReachabilityRef from
                         host name (as a C string) or address (as a
                         sockaddr)
                    • Get network info with
                         SCNetworkReachabilityGetFlags()




Monday, January 16, 12
Reachability Flags
          enum {
              kSCNetworkReachabilityFlagsTransientConnection = 1<<0,
              kSCNetworkReachabilityFlagsReachable = 1<<1,
              kSCNetworkReachabilityFlagsConnectionRequired = 1<<2,
              kSCNetworkReachabilityFlagsConnectionOnTraffic = 1<<3,
              kSCNetworkReachabilityFlagsInterventionRequired = 1<<4,
              kSCNetworkReachabilityFlagsConnectionOnDemand = 1<<5,
              kSCNetworkReachabilityFlagsIsLocalAddress = 1<<16,
              kSCNetworkReachabilityFlagsIsDirect = 1<<17,
              kSCNetworkReachabilityFlagsIsWWAN = 1<<18,
              kSCNetworkReachabilityFlagsConnectionAutomatic     =
                  kSCNetworkReachabilityFlagsConnectionOnTraffic
          };
          typedef     uint32_t    SCNetworkReachabilityFlags;




Monday, January 16, 12
Reachability callbacks

                    • Networks come and go; your app should
                         handle this
                    • SCNetworkReachabilitySetCallback()
                         MyNetworkReachabilityCallBack(
                             SCNetworkReachabilityRef target,
                             SCNetworkReachabilityFlags flags,
                             void *info
                         );


Monday, January 16, 12
Monday, January 16, 12
http://mattgemmell.com/2011/07/25/network-link-
                           conditioner-in-lion/
Monday, January 16, 12
Assuming the network
                        is working…


Monday, January 16, 12
Say hello to iCloud



Monday, January 16, 12
The iCloud API

                    •
                    •
                    •
                    •
                    •

Monday, January 16, 12
iCloud: UIDocument
                    • iCloud does not have its own API, per se
                    • Special case of saving documents
                     • Same code to save to local or cloud
                           documents directory by URL
                         • There are also iCloud APIs for simple
                           key-value storage, and Core Data
                           persistent stores


Monday, January 16, 12
iCloud set-up
                  Enable iCloud for AppID in provisioning portal



                         Enable entitlements in .xcodeproj (also
                               creates .entitlements file)




Monday, January 16, 12
Browsing in iCloud

                    • Compose an NSMetadataQuery (from
                         Spotlight API)
                    • Include
                      NSMetadataQueryUbiquitousDocu
                         mentsScope in search scopes

                    • Start search (asynchronous!)

Monday, January 16, 12
-(void) refreshNotes {
      NSLog (@"refreshNotes");
      [self.noteDictsArray removeAllObjects];
      self.currentQuery = [[NSMetadataQuery alloc] init];
      // register for notifications
      [[NSNotificationCenter defaultCenter] addObserver:self
                                               selector:@selector(queryDidUpdate:)
                                       name:NSMetadataQueryDidUpdateNotification
                                                 object:self.currentQuery];

         [[NSNotificationCenter defaultCenter] addObserver:self
                                                  selector:@selector(initalGatherComplete:)
                                          name:NSMetadataQueryDidFinishGatheringNotification
                                                    object:self.currentQuery];




Monday, January 16, 12
// Configure the search predicate
           NSPredicate *searchPredicate;
           searchPredicate=[NSPredicate predicateWithFormat:@"%K LIKE %@",
                            NSMetadataItemFSNameKey, @"*.cloudnote"];
           [self.currentQuery setPredicate:searchPredicate];

           // Set the search scope to only search iCloud
           NSArray *searchScopes;
           searchScopes=[NSArray arrayWithObjects:
                         NSMetadataQueryUbiquitousDocumentsScope,nil];
           [self.currentQuery setSearchScopes:searchScopes];

           // Start the query!
          [self.currentQuery startQuery];




Monday, January 16, 12
- (void)initalGatherComplete:sender; {
    // Stop the query, the single pass is completed.
    [self.currentQuery stopQuery];
    for (int i=0; i < [self.currentQuery resultCount]; i++) {
        NSMetadataItem *noteMetadata = [self.currentQuery resultAtIndex:i];
        NSString *noteName = [noteMetadata
                        valueForAttribute:NSMetadataItemDisplayNameKey];
        NSURL *noteURL = [noteMetadata valueForAttribute:NSMetadataItemURLKey];
        NSDate *noteModifiedDate = [noteMetadata
                        valueForAttribute:NSMetadataItemFSContentChangeDateKey];
        NSLog(@"%@: %@", noteName, noteURL);
        NSDictionary *noteDict = [NSDictionary dictionaryWithObjectsAndKeys:
                                   noteName, NSMetadataItemDisplayNameKey,
                                   noteURL, NSMetadataItemURLKey,
                                   noteModifiedDate,
                        NSMetadataItemFSContentChangeDateKey,
                                   nil];
        [self.noteDictsArray addObject:noteDict];
    }




Monday, January 16, 12
Monday, January 16, 12
But what about
                         document contents?


Monday, January 16, 12
iCloud documents


                    • Subclass UIDocument (new in iOS 5)
                    • Override contentsForType: and
                      loadFromContents:ofType:error:




Monday, January 16, 12
UIDocument overrides
    - (id)contentsForType:(NSString *)typeName error:(NSError **)outError {
        NSLog (@"archiving: %@", self.noteDict);
        return [NSKeyedArchiver archivedDataWithRootObject:self.noteDict];
    }



    - (BOOL)loadFromContents:(id)contents
                      ofType:(NSString *)typeName
                        error:(NSError *__autoreleasing *)outError {
        BOOL success = NO;
        if([contents isKindOfClass:[NSData class]] && [contents length] > 0) {
            NSData *data = (NSData *)contents;
            self.noteDict = [NSMutableDictionary dictionaryWithDictionary:
                              [NSKeyedUnarchiver unarchiveObjectWithData:data]];
            success = YES;
        }
        NSLog (@"noteDict: %@", self.noteDict);
        return success;
    }


Monday, January 16, 12
Start a new document
                            in iCloud
   NSFileManager *fm = [NSFileManager defaultManager];
   NSURL *newDocumentURL = [fm URLForUbiquityContainerIdentifier:nil];

   newDocumentURL = [newDocumentURL
                     URLByAppendingPathComponent:@"Documents"
                     isDirectory:YES];
   // fileName calculation omitted
   newDocumentURL = [newDocumentURL
                     URLByAppendingPathComponent:fileName];
   CDMNoteDocument *doc = [[CDMNoteDocument alloc] initWithFileURL:newDocumentURL];
   // Save the new document to disk.
   [doc saveToURL:newDocumentURL
       forSaveOperation:UIDocumentSaveForCreating
       completionHandler:^(BOOL success) {
           NSLog (@"new document %@ saved",
                  success ? @"was" : @"was not");
       }];




Monday, January 16, 12
Open an existing
                         iCloud document

             NSURL *noteURL = (NSURL*) [noteDict valueForKey:NSMetadataItemURLKey];
             CDMNoteDocument *doc = [[CDMNoteDocument alloc] initWithFileURL:noteURL];
             [doc openWithCompletionHandler:^(BOOL success){
                 NSLog (@"opening doc at %@ %@",
                        doc.fileURL,
                        success ? @"succeeded" : @"failed");
             }




Monday, January 16, 12
Saving changes

                 [note updateChangeCount:UIDocumentChangeDone];

                 [note closeWithCompletionHandler:^(BOOL success) {
                     NSLog (@"document close was %@",
                            success ? @"successful" : @"not successful");
                 }];




Monday, January 16, 12
Detecting iCloud
                              conflicts
                    • Register for NSNotificationCenter for
                         UIDocumentStateChangedNotification
                    • Inspect the documentState property for
                         the value UIDocumentStateInConflict
                    • Use NSFileVersion method
                         unresolvedConflictVersionsOfItemAtURL
                         to inspect the versions


Monday, January 16, 12
Demo: CloudNotes




Monday, January 16, 12
But what if my data
                           isn’t in iCloud?


Monday, January 16, 12
Networking in
                            Foundation
                    • NSURL
                    • Classes that load from URLs
                    • Property lists
                    • URL Loading System

Monday, January 16, 12
initWithContentsOfURL:


                    • Supported by NSString, NSData
                    • Also NSArray and NSDictionary if contents
                         are a property list
                    • These calls block!


Monday, January 16, 12
URL Loading System
                    • NSURL + NSURLRequest +
                         NSURLConnection + delegate callbacks
                         • connection:didReceiveResponse:,
                           connection:didReceiveData:, etc.
                    • Fairly deep HTTP support (incl.
                         authentication)
                    • Not an arbitrary socket networking API
Monday, January 16, 12
But I want to host a
                         server on my iPhone!


Monday, January 16, 12
CFNetwork

                    • C-based API, abstractions over network
                         protocols and BSD sockets
                    • Deep support for HTTP, HTTPS, FTP, DNS
                    • Built to work asynchronously in RunLoop-
                         based applications (incl. Cocoa Touch)



Monday, January 16, 12
If you must run a
                                 server
                    • Create CFSocketRef with
                         CFSocketCreate() [or similar] setting
                         callbackTypes to kCFSocketAcceptCallback
                    • Callback receives a CFSocketNativeHandle
                    • From this,
                         CFStreamCreatePairWithSocket() to get
                         CFReadStreamRef and CFWriteStreamRef


Monday, January 16, 12
Network Discovery



Monday, January 16, 12
Bonjour!
                    • Protocol for address self-assignment and
                         service discovery
                    • Published ZEROCONF standard
                    • Open-source implementations for Mac,
                         Windows, Linux, Java
                    • APIs: NSNetService and CFNetServiceRef

Monday, January 16, 12
Searching for Bonjour
                              http servers
             -(void) startSearchingForWebServers {
             ! NSNetServiceBrowser bonjourBrowser = [[NSNetServiceBrowser alloc] init];
             ! [bonjourBrowser setDelegate: self];
             ! [bonjourBrowser searchForServicesOfType:@"_http._tcp" inDomain:@""];
             }



            - (void)netServiceBrowser:(NSNetServiceBrowser *)netServiceBrowser
                   didFindService:(NSNetService *)netService
                       moreComing:(BOOL)moreServicesComing {
            ! [discoveredWebServices addObject: netService];
            ! [tableView reloadData];
            ! if (! moreServicesComing)
            ! !    [activityIndicator stopAnimating];
            }




Monday, January 16, 12
Got a service,now
                                what?
                    • Bonjour provides the discovery, not the
                         service itself
                    • The NSNetService object includes
                         addresses, host name, and port
                    • Client connects to the host via
                         NSURLConnection, CFNetwork, etc.



Monday, January 16, 12
GameKit

                    • Simplified Bonjour over Bluetooth or WiFi
                    • GKPeerPickerController UI for peer
                         discovery
                    • APIs allow client-server or peer-to-peer


Monday, January 16, 12
GKSession

                    • All about the delegate callbacks:
                     • didReceiveConnectionRequestFromPeer:
                     • peer:didChangeState:
                     • receiveData:fromPeer:inSession:

Monday, January 16, 12
Demo (if we are really,
                       really lucky)




Monday, January 16, 12
GameKit voice chat

                    • Set up through Game Center
                    • Create with -[GKMatch
                         voiceChatWithName:]
                    • Does anyone use this?


Monday, January 16, 12
Speaking of media…



Monday, January 16, 12
HTTP Live Streaming
                    • Firewall-friendly audio/video streaming for
                         iOS and Mac OS X 10.6+ (replaces RTP/
                         RTSP)
                    • Required for any app that streams more
                         than 10MB over mobile network
                    • Client support: AVPlayer,
                         MPMoviePlayerController


Monday, January 16, 12
HLS: How It Works
                    • Segmenting server splits source media into
                         separate files (usually .m4a for audio-
                         only, .ts for A/V), usually 10 seconds each,
                         and creates an .m3u8 playlist file
                    • Playlist may point to bandwidth-appropriate
                         playlists
                    • Clients continually reload playlist, fetch the
                         segments, queue them up


Monday, January 16, 12
Sample playlist
                         #EXTM3U
                         #EXT-X-TARGETDURATION:8
                         #EXT-X-MEDIA-SEQUENCE:0
                         #EXTINF:8,
                         0640/0640_090110_120505_0.ts
                         #EXTINF:8,
                         0640/0640_090110_120505_1.ts
                         #EXTINF:8,
                         0640/0640_090110_120505_2.ts
                         #EXTINF:8,
                         0640/0640_090110_120505_3.ts
                         #EXTINF:8,
                         0640/0640_090110_120505_4.ts




Monday, January 16, 12
Bandwidth-delimited
                              playlist

        #EXTM3U
        #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1280000
        http://example.com/low.m3u8
        #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2560000
        http://example.com/mid.m3u8
        #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=7680000
        http://example.com/hi.m3u8




Monday, January 16, 12
Demo: HLS bandwidth




Monday, January 16, 12
Takeaways



Monday, January 16, 12
iOS Priorities
                    • Asynchronicity — don’t block the UI
                     • Many network APIs are difficult or
                          impossible to block on
                    • Domain-appropriate abstractions
                     • iCloud, GameKit, HLS
                    • You don’t need to know the difference
                         between cellular and wifi


Monday, January 16, 12
End of line.



Monday, January 16, 12

More Related Content

PDF
Beginning icloud development - Cesare Rocchi - WhyMCA
Whymca
 
KEY
Data perisistence in iOS
mobiledeveloperpl
 
KEY
Whats new in iOS5
Paul Ardeleanu
 
KEY
iOS5 NewStuff
deenna_vargilz
 
PDF
High Performance Core Data
Matthew Morey
 
PDF
Core Data with multiple managed object contexts
Matthew Morey
 
PDF
NoSQL and JavaScript: a Love Story
Alexandre Morgaut
 
PDF
ERGroupware
WO Community
 
Beginning icloud development - Cesare Rocchi - WhyMCA
Whymca
 
Data perisistence in iOS
mobiledeveloperpl
 
Whats new in iOS5
Paul Ardeleanu
 
iOS5 NewStuff
deenna_vargilz
 
High Performance Core Data
Matthew Morey
 
Core Data with multiple managed object contexts
Matthew Morey
 
NoSQL and JavaScript: a Love Story
Alexandre Morgaut
 
ERGroupware
WO Community
 

What's hot (20)

PDF
Adventures in Multithreaded Core Data
Inferis
 
PDF
Client Server Communication on iOS
Make School
 
KEY
iOSDevCamp 2011 Core Data
Chris Mar
 
PPTX
Getting Started with Datatsax .Net Driver
DataStax Academy
 
PDF
20120121
komarineko
 
PDF
Via forensics icloud-keychain_passwords_13
viaForensics
 
PPTX
Oak Lucene Indexes
Chetan Mehrotra
 
PDF
Http4s, Doobie and Circe: The Functional Web Stack
GaryCoady
 
PPTX
Examiness hints and tips from the trenches
Ismail Mayat
 
PPTX
Getting started with Elasticsearch and .NET
Tomas Jansson
 
PDF
Multi-threaded CoreData Done Right
morrowa_de
 
PPTX
ElasticSearch for .NET Developers
Ben van Mol
 
PDF
Java Persistence Frameworks for MongoDB
MongoDB
 
PPTX
Cassandra 2.2 & 3.0
Victor Coustenoble
 
PDF
Webinar: MongoDB Persistence with Java and Morphia
MongoDB
 
PDF
Cloudera Impala, updated for v1.0
Scott Leberknight
 
PDF
Cutting Edge Data Processing with PHP & XQuery
William Candillon
 
PPTX
Offline survival in the deadzone
Scott Steinbeck, MBA
 
PDF
Symfony Day 2010 Doctrine MongoDB ODM
Jonathan Wage
 
PDF
Painless Persistence in a Disconnected World
Christian Melchior
 
Adventures in Multithreaded Core Data
Inferis
 
Client Server Communication on iOS
Make School
 
iOSDevCamp 2011 Core Data
Chris Mar
 
Getting Started with Datatsax .Net Driver
DataStax Academy
 
20120121
komarineko
 
Via forensics icloud-keychain_passwords_13
viaForensics
 
Oak Lucene Indexes
Chetan Mehrotra
 
Http4s, Doobie and Circe: The Functional Web Stack
GaryCoady
 
Examiness hints and tips from the trenches
Ismail Mayat
 
Getting started with Elasticsearch and .NET
Tomas Jansson
 
Multi-threaded CoreData Done Right
morrowa_de
 
ElasticSearch for .NET Developers
Ben van Mol
 
Java Persistence Frameworks for MongoDB
MongoDB
 
Cassandra 2.2 & 3.0
Victor Coustenoble
 
Webinar: MongoDB Persistence with Java and Morphia
MongoDB
 
Cloudera Impala, updated for v1.0
Scott Leberknight
 
Cutting Edge Data Processing with PHP & XQuery
William Candillon
 
Offline survival in the deadzone
Scott Steinbeck, MBA
 
Symfony Day 2010 Doctrine MongoDB ODM
Jonathan Wage
 
Painless Persistence in a Disconnected World
Christian Melchior
 
Ad

Viewers also liked (6)

PDF
Bonjour Android, it's ZeroConf
Roberto Orgiu
 
PPT
Fuzz Testing-Atul Khot
bhumika2108
 
PDF
Bonjour for Java
Hendrik Ebbers
 
PPT
Php Basic Security
mussawir20
 
KEY
Icloud keynote2
avsorrent
 
PDF
iCloud
Andri Yadi
 
Bonjour Android, it's ZeroConf
Roberto Orgiu
 
Fuzz Testing-Atul Khot
bhumika2108
 
Bonjour for Java
Hendrik Ebbers
 
Php Basic Security
mussawir20
 
Icloud keynote2
avsorrent
 
iCloud
Andri Yadi
 
Ad

Similar to Bonjour, iCloud (20)

PPTX
IOT/Mobile/Cloud - Next Connected World
Ravi Dalmia
 
KEY
iPhone project - Wireless networks seminar
Silvio Daminato
 
PDF
02 Objective C
Mahmoud
 
PPTX
AFNetworking
joaopmaia
 
PDF
Learn to love networking on iOS
Paolo Tagliani
 
PDF
ASFWS 2012 - Audit d’applications iOS par Julien Bachmann
Cyber Security Alliance
 
PDF
iOS Development - Offline Class for Jasakomer
Andri Yadi
 
PDF
iPhonical and model-driven software development for the iPhone
Heiko Behrens
 
PPTX
Basic iOS Training with SWIFT - Part 4
Manoj Ellappan
 
PDF
iOS Development. Some practices.
Alexander Lobunets
 
PDF
KKBOX WWDC17 Security - Antony
Liyao Chen
 
PPTX
Pentesting iOS Applications
jasonhaddix
 
PDF
Building Papers
Mahmoud
 
PDF
Cocoa fundamentalswert
Saygın Topatan
 
PDF
iOS5 开发新特性
yangdj
 
PDF
FI MUNI 2012 - iOS Basics
Petr Dvorak
 
PDF
iOS Application Security
Egor Tolstoy
 
PDF
Write native iPhone applications using Eclipse CDT
Atit Patumvan
 
PDF
Native Phone Development 101
Sasmito Adibowo
 
PDF
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
Taro Matsuzawa
 
IOT/Mobile/Cloud - Next Connected World
Ravi Dalmia
 
iPhone project - Wireless networks seminar
Silvio Daminato
 
02 Objective C
Mahmoud
 
AFNetworking
joaopmaia
 
Learn to love networking on iOS
Paolo Tagliani
 
ASFWS 2012 - Audit d’applications iOS par Julien Bachmann
Cyber Security Alliance
 
iOS Development - Offline Class for Jasakomer
Andri Yadi
 
iPhonical and model-driven software development for the iPhone
Heiko Behrens
 
Basic iOS Training with SWIFT - Part 4
Manoj Ellappan
 
iOS Development. Some practices.
Alexander Lobunets
 
KKBOX WWDC17 Security - Antony
Liyao Chen
 
Pentesting iOS Applications
jasonhaddix
 
Building Papers
Mahmoud
 
Cocoa fundamentalswert
Saygın Topatan
 
iOS5 开发新特性
yangdj
 
FI MUNI 2012 - iOS Basics
Petr Dvorak
 
iOS Application Security
Egor Tolstoy
 
Write native iPhone applications using Eclipse CDT
Atit Patumvan
 
Native Phone Development 101
Sasmito Adibowo
 
スマートフォン勉強会@関東 #11 どう考えてもdisconなものをiPhoneに移植してみた
Taro Matsuzawa
 

More from Chris Adamson (20)

PDF
Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)
Chris Adamson
 
PDF
Whatever Happened to Visual Novel Anime? (JAFAX 2018)
Chris Adamson
 
PDF
Media Frameworks Versus Swift (Swift by Northwest, October 2017)
Chris Adamson
 
PDF
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...
Chris Adamson
 
PDF
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
Chris Adamson
 
PDF
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
Chris Adamson
 
PDF
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...
Chris Adamson
 
PDF
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
Chris Adamson
 
PDF
Firebase: Totally Not Parse All Over Again (Unless It Is)
Chris Adamson
 
PDF
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
Chris Adamson
 
PDF
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
Chris Adamson
 
PDF
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
Chris Adamson
 
PDF
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Chris Adamson
 
PDF
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014
Chris Adamson
 
PDF
Stupid Video Tricks, CocoaConf Seattle 2014
Chris Adamson
 
PDF
Stupid Video Tricks, CocoaConf Las Vegas
Chris Adamson
 
PDF
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Chris Adamson
 
PDF
Stupid Video Tricks (CocoaConf DC, March 2014)
Chris Adamson
 
PDF
Stupid Video Tricks
Chris Adamson
 
PDF
Introduction to the Roku SDK
Chris Adamson
 
Whatever Happened to Visual Novel Anime? (AWA/Youmacon 2018)
Chris Adamson
 
Whatever Happened to Visual Novel Anime? (JAFAX 2018)
Chris Adamson
 
Media Frameworks Versus Swift (Swift by Northwest, October 2017)
Chris Adamson
 
Fall Premieres: Media Frameworks in iOS 11, macOS 10.13, and tvOS 11 (CocoaCo...
Chris Adamson
 
CocoaConf Chicago 2017: Media Frameworks and Swift: This Is Fine
Chris Adamson
 
Forward Swift 2017: Media Frameworks and Swift: This Is Fine
Chris Adamson
 
Firebase: Totally Not Parse All Over Again (Unless It Is) (CocoaConf San Jose...
Chris Adamson
 
Building A Streaming Apple TV App (CocoaConf San Jose, Nov 2016)
Chris Adamson
 
Firebase: Totally Not Parse All Over Again (Unless It Is)
Chris Adamson
 
Building A Streaming Apple TV App (CocoaConf DC, Sept 2016)
Chris Adamson
 
Video Killed the Rolex Star (CocoaConf San Jose, November, 2015)
Chris Adamson
 
Video Killed the Rolex Star (CocoaConf Columbus, July 2015)
Chris Adamson
 
Revenge of the 80s: Cut/Copy/Paste, Undo/Redo, and More Big Hits (CocoaConf C...
Chris Adamson
 
Core Image: The Most Fun API You're Not Using, CocoaConf Atlanta, December 2014
Chris Adamson
 
Stupid Video Tricks, CocoaConf Seattle 2014
Chris Adamson
 
Stupid Video Tricks, CocoaConf Las Vegas
Chris Adamson
 
Core Image: The Most Fun API You're Not Using (CocoaConf Columbus 2014)
Chris Adamson
 
Stupid Video Tricks (CocoaConf DC, March 2014)
Chris Adamson
 
Stupid Video Tricks
Chris Adamson
 
Introduction to the Roku SDK
Chris Adamson
 

Recently uploaded (20)

PDF
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
PDF
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
PDF
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PPTX
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
PDF
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
Structs to JSON: How Go Powers REST APIs
Emily Achieng
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Advances in Ultra High Voltage (UHV) Transmission and Distribution Systems.pdf
Nabajyoti Banik
 
AI-Cloud-Business-Management-Platforms-The-Key-to-Efficiency-Growth.pdf
Artjoker Software Development Company
 
Economic Impact of Data Centres to the Malaysian Economy
flintglobalapac
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
Doc9.....................................
SofiaCollazos
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
cloud computing vai.pptx for the project
vaibhavdobariyal79
 
Get More from Fiori Automation - What’s New, What Works, and What’s Next.pdf
Precisely
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 

Bonjour, iCloud

  • 1. iOS Networking: Bonjour, iCloud! Chris Adamson • @invalidname CodeMash 2012 Monday, January 16, 12
  • 2. What we’ll cover • Obvious networking APIs • iCloud, Bonjour, GameKit, CFNetwork • Not-so-obvious networking APIs • Foundation, media APIs, System Configuration Monday, January 16, 12
  • 3. The first thing your network app should do? Monday, January 16, 12
  • 5. Do I have network access at all? Monday, January 16, 12
  • 6. Reachability • Defined in SystemConfiguration.framework • C-based API, Obj-C wrapper available as sample code from Apple • Your network-based app will be rejected if it turtles without network access Monday, January 16, 12
  • 8. Reachability • Create a SCNetworkReachabilityRef from host name (as a C string) or address (as a sockaddr) • Get network info with SCNetworkReachabilityGetFlags() Monday, January 16, 12
  • 9. Reachability Flags enum { kSCNetworkReachabilityFlagsTransientConnection = 1<<0, kSCNetworkReachabilityFlagsReachable = 1<<1, kSCNetworkReachabilityFlagsConnectionRequired = 1<<2, kSCNetworkReachabilityFlagsConnectionOnTraffic = 1<<3, kSCNetworkReachabilityFlagsInterventionRequired = 1<<4, kSCNetworkReachabilityFlagsConnectionOnDemand = 1<<5, kSCNetworkReachabilityFlagsIsLocalAddress = 1<<16, kSCNetworkReachabilityFlagsIsDirect = 1<<17, kSCNetworkReachabilityFlagsIsWWAN = 1<<18, kSCNetworkReachabilityFlagsConnectionAutomatic = kSCNetworkReachabilityFlagsConnectionOnTraffic }; typedef uint32_t SCNetworkReachabilityFlags; Monday, January 16, 12
  • 10. Reachability callbacks • Networks come and go; your app should handle this • SCNetworkReachabilitySetCallback() MyNetworkReachabilityCallBack( SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info ); Monday, January 16, 12
  • 13. Assuming the network is working… Monday, January 16, 12
  • 14. Say hello to iCloud Monday, January 16, 12
  • 15. The iCloud API • • • • • Monday, January 16, 12
  • 16. iCloud: UIDocument • iCloud does not have its own API, per se • Special case of saving documents • Same code to save to local or cloud documents directory by URL • There are also iCloud APIs for simple key-value storage, and Core Data persistent stores Monday, January 16, 12
  • 17. iCloud set-up Enable iCloud for AppID in provisioning portal Enable entitlements in .xcodeproj (also creates .entitlements file) Monday, January 16, 12
  • 18. Browsing in iCloud • Compose an NSMetadataQuery (from Spotlight API) • Include NSMetadataQueryUbiquitousDocu mentsScope in search scopes • Start search (asynchronous!) Monday, January 16, 12
  • 19. -(void) refreshNotes { NSLog (@"refreshNotes"); [self.noteDictsArray removeAllObjects]; self.currentQuery = [[NSMetadataQuery alloc] init]; // register for notifications [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(queryDidUpdate:) name:NSMetadataQueryDidUpdateNotification object:self.currentQuery]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(initalGatherComplete:) name:NSMetadataQueryDidFinishGatheringNotification object:self.currentQuery]; Monday, January 16, 12
  • 20. // Configure the search predicate NSPredicate *searchPredicate; searchPredicate=[NSPredicate predicateWithFormat:@"%K LIKE %@", NSMetadataItemFSNameKey, @"*.cloudnote"]; [self.currentQuery setPredicate:searchPredicate]; // Set the search scope to only search iCloud NSArray *searchScopes; searchScopes=[NSArray arrayWithObjects: NSMetadataQueryUbiquitousDocumentsScope,nil]; [self.currentQuery setSearchScopes:searchScopes]; // Start the query! [self.currentQuery startQuery]; Monday, January 16, 12
  • 21. - (void)initalGatherComplete:sender; { // Stop the query, the single pass is completed. [self.currentQuery stopQuery]; for (int i=0; i < [self.currentQuery resultCount]; i++) { NSMetadataItem *noteMetadata = [self.currentQuery resultAtIndex:i]; NSString *noteName = [noteMetadata valueForAttribute:NSMetadataItemDisplayNameKey]; NSURL *noteURL = [noteMetadata valueForAttribute:NSMetadataItemURLKey]; NSDate *noteModifiedDate = [noteMetadata valueForAttribute:NSMetadataItemFSContentChangeDateKey]; NSLog(@"%@: %@", noteName, noteURL); NSDictionary *noteDict = [NSDictionary dictionaryWithObjectsAndKeys: noteName, NSMetadataItemDisplayNameKey, noteURL, NSMetadataItemURLKey, noteModifiedDate, NSMetadataItemFSContentChangeDateKey, nil]; [self.noteDictsArray addObject:noteDict]; } Monday, January 16, 12
  • 23. But what about document contents? Monday, January 16, 12
  • 24. iCloud documents • Subclass UIDocument (new in iOS 5) • Override contentsForType: and loadFromContents:ofType:error: Monday, January 16, 12
  • 25. UIDocument overrides - (id)contentsForType:(NSString *)typeName error:(NSError **)outError { NSLog (@"archiving: %@", self.noteDict); return [NSKeyedArchiver archivedDataWithRootObject:self.noteDict]; } - (BOOL)loadFromContents:(id)contents ofType:(NSString *)typeName error:(NSError *__autoreleasing *)outError { BOOL success = NO; if([contents isKindOfClass:[NSData class]] && [contents length] > 0) { NSData *data = (NSData *)contents; self.noteDict = [NSMutableDictionary dictionaryWithDictionary: [NSKeyedUnarchiver unarchiveObjectWithData:data]]; success = YES; } NSLog (@"noteDict: %@", self.noteDict); return success; } Monday, January 16, 12
  • 26. Start a new document in iCloud NSFileManager *fm = [NSFileManager defaultManager]; NSURL *newDocumentURL = [fm URLForUbiquityContainerIdentifier:nil]; newDocumentURL = [newDocumentURL URLByAppendingPathComponent:@"Documents" isDirectory:YES]; // fileName calculation omitted newDocumentURL = [newDocumentURL URLByAppendingPathComponent:fileName]; CDMNoteDocument *doc = [[CDMNoteDocument alloc] initWithFileURL:newDocumentURL]; // Save the new document to disk. [doc saveToURL:newDocumentURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) { NSLog (@"new document %@ saved", success ? @"was" : @"was not"); }]; Monday, January 16, 12
  • 27. Open an existing iCloud document NSURL *noteURL = (NSURL*) [noteDict valueForKey:NSMetadataItemURLKey]; CDMNoteDocument *doc = [[CDMNoteDocument alloc] initWithFileURL:noteURL]; [doc openWithCompletionHandler:^(BOOL success){ NSLog (@"opening doc at %@ %@", doc.fileURL, success ? @"succeeded" : @"failed"); } Monday, January 16, 12
  • 28. Saving changes [note updateChangeCount:UIDocumentChangeDone]; [note closeWithCompletionHandler:^(BOOL success) { NSLog (@"document close was %@", success ? @"successful" : @"not successful"); }]; Monday, January 16, 12
  • 29. Detecting iCloud conflicts • Register for NSNotificationCenter for UIDocumentStateChangedNotification • Inspect the documentState property for the value UIDocumentStateInConflict • Use NSFileVersion method unresolvedConflictVersionsOfItemAtURL to inspect the versions Monday, January 16, 12
  • 31. But what if my data isn’t in iCloud? Monday, January 16, 12
  • 32. Networking in Foundation • NSURL • Classes that load from URLs • Property lists • URL Loading System Monday, January 16, 12
  • 33. initWithContentsOfURL: • Supported by NSString, NSData • Also NSArray and NSDictionary if contents are a property list • These calls block! Monday, January 16, 12
  • 34. URL Loading System • NSURL + NSURLRequest + NSURLConnection + delegate callbacks • connection:didReceiveResponse:, connection:didReceiveData:, etc. • Fairly deep HTTP support (incl. authentication) • Not an arbitrary socket networking API Monday, January 16, 12
  • 35. But I want to host a server on my iPhone! Monday, January 16, 12
  • 36. CFNetwork • C-based API, abstractions over network protocols and BSD sockets • Deep support for HTTP, HTTPS, FTP, DNS • Built to work asynchronously in RunLoop- based applications (incl. Cocoa Touch) Monday, January 16, 12
  • 37. If you must run a server • Create CFSocketRef with CFSocketCreate() [or similar] setting callbackTypes to kCFSocketAcceptCallback • Callback receives a CFSocketNativeHandle • From this, CFStreamCreatePairWithSocket() to get CFReadStreamRef and CFWriteStreamRef Monday, January 16, 12
  • 39. Bonjour! • Protocol for address self-assignment and service discovery • Published ZEROCONF standard • Open-source implementations for Mac, Windows, Linux, Java • APIs: NSNetService and CFNetServiceRef Monday, January 16, 12
  • 40. Searching for Bonjour http servers -(void) startSearchingForWebServers { ! NSNetServiceBrowser bonjourBrowser = [[NSNetServiceBrowser alloc] init]; ! [bonjourBrowser setDelegate: self]; ! [bonjourBrowser searchForServicesOfType:@"_http._tcp" inDomain:@""]; } - (void)netServiceBrowser:(NSNetServiceBrowser *)netServiceBrowser didFindService:(NSNetService *)netService moreComing:(BOOL)moreServicesComing { ! [discoveredWebServices addObject: netService]; ! [tableView reloadData]; ! if (! moreServicesComing) ! ! [activityIndicator stopAnimating]; } Monday, January 16, 12
  • 41. Got a service,now what? • Bonjour provides the discovery, not the service itself • The NSNetService object includes addresses, host name, and port • Client connects to the host via NSURLConnection, CFNetwork, etc. Monday, January 16, 12
  • 42. GameKit • Simplified Bonjour over Bluetooth or WiFi • GKPeerPickerController UI for peer discovery • APIs allow client-server or peer-to-peer Monday, January 16, 12
  • 43. GKSession • All about the delegate callbacks: • didReceiveConnectionRequestFromPeer: • peer:didChangeState: • receiveData:fromPeer:inSession: Monday, January 16, 12
  • 44. Demo (if we are really, really lucky) Monday, January 16, 12
  • 45. GameKit voice chat • Set up through Game Center • Create with -[GKMatch voiceChatWithName:] • Does anyone use this? Monday, January 16, 12
  • 47. HTTP Live Streaming • Firewall-friendly audio/video streaming for iOS and Mac OS X 10.6+ (replaces RTP/ RTSP) • Required for any app that streams more than 10MB over mobile network • Client support: AVPlayer, MPMoviePlayerController Monday, January 16, 12
  • 48. HLS: How It Works • Segmenting server splits source media into separate files (usually .m4a for audio- only, .ts for A/V), usually 10 seconds each, and creates an .m3u8 playlist file • Playlist may point to bandwidth-appropriate playlists • Clients continually reload playlist, fetch the segments, queue them up Monday, January 16, 12
  • 49. Sample playlist #EXTM3U #EXT-X-TARGETDURATION:8 #EXT-X-MEDIA-SEQUENCE:0 #EXTINF:8, 0640/0640_090110_120505_0.ts #EXTINF:8, 0640/0640_090110_120505_1.ts #EXTINF:8, 0640/0640_090110_120505_2.ts #EXTINF:8, 0640/0640_090110_120505_3.ts #EXTINF:8, 0640/0640_090110_120505_4.ts Monday, January 16, 12
  • 50. Bandwidth-delimited playlist #EXTM3U #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=1280000 http://example.com/low.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=2560000 http://example.com/mid.m3u8 #EXT-X-STREAM-INF:PROGRAM-ID=1,BANDWIDTH=7680000 http://example.com/hi.m3u8 Monday, January 16, 12
  • 51. Demo: HLS bandwidth Monday, January 16, 12
  • 53. iOS Priorities • Asynchronicity — don’t block the UI • Many network APIs are difficult or impossible to block on • Domain-appropriate abstractions • iCloud, GameKit, HLS • You don’t need to know the difference between cellular and wifi Monday, January 16, 12
  • 54. End of line. Monday, January 16, 12