SlideShare a Scribd company logo
1 of 54
Download to read offline
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

What's hot

Adventures in Multithreaded Core Data
Adventures in Multithreaded Core DataAdventures in Multithreaded Core Data
Adventures in Multithreaded Core Data
Inferis
 
Getting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverGetting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net Driver
DataStax Academy
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
MongoDB
 
Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODM
Jonathan Wage
 

What's hot (20)

Adventures in Multithreaded Core Data
Adventures in Multithreaded Core DataAdventures in Multithreaded Core Data
Adventures in Multithreaded Core Data
 
Client Server Communication on iOS
Client Server Communication on iOSClient Server Communication on iOS
Client Server Communication on iOS
 
iOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core DataiOSDevCamp 2011 Core Data
iOSDevCamp 2011 Core Data
 
Getting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net DriverGetting Started with Datatsax .Net Driver
Getting Started with Datatsax .Net Driver
 
20120121
2012012120120121
20120121
 
Via forensics icloud-keychain_passwords_13
Via forensics icloud-keychain_passwords_13Via forensics icloud-keychain_passwords_13
Via forensics icloud-keychain_passwords_13
 
Oak Lucene Indexes
Oak Lucene IndexesOak Lucene Indexes
Oak Lucene Indexes
 
Http4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web StackHttp4s, Doobie and Circe: The Functional Web Stack
Http4s, Doobie and Circe: The Functional Web Stack
 
Examiness hints and tips from the trenches
Examiness hints and tips from the trenchesExaminess hints and tips from the trenches
Examiness hints and tips from the trenches
 
Getting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NETGetting started with Elasticsearch and .NET
Getting started with Elasticsearch and .NET
 
Multi-threaded CoreData Done Right
Multi-threaded CoreData Done RightMulti-threaded CoreData Done Right
Multi-threaded CoreData Done Right
 
ElasticSearch for .NET Developers
ElasticSearch for .NET DevelopersElasticSearch for .NET Developers
ElasticSearch for .NET Developers
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Cassandra 2.2 & 3.0
Cassandra 2.2 & 3.0Cassandra 2.2 & 3.0
Cassandra 2.2 & 3.0
 
Webinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and MorphiaWebinar: MongoDB Persistence with Java and Morphia
Webinar: MongoDB Persistence with Java and Morphia
 
Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0Cloudera Impala, updated for v1.0
Cloudera Impala, updated for v1.0
 
Cutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQueryCutting Edge Data Processing with PHP & XQuery
Cutting Edge Data Processing with PHP & XQuery
 
Offline survival in the deadzone
Offline survival in the deadzoneOffline survival in the deadzone
Offline survival in the deadzone
 
Symfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODMSymfony Day 2010 Doctrine MongoDB ODM
Symfony Day 2010 Doctrine MongoDB ODM
 
Painless Persistence in a Disconnected World
Painless Persistence in a Disconnected WorldPainless Persistence in a Disconnected World
Painless Persistence in a Disconnected World
 

Viewers also liked (6)

Bonjour Android, it's ZeroConf
Bonjour Android, it's ZeroConfBonjour Android, it's ZeroConf
Bonjour Android, it's ZeroConf
 
Fuzz Testing-Atul Khot
Fuzz Testing-Atul KhotFuzz Testing-Atul Khot
Fuzz Testing-Atul Khot
 
Bonjour for Java
Bonjour for JavaBonjour for Java
Bonjour for Java
 
Php Basic Security
Php Basic SecurityPhp Basic Security
Php Basic Security
 
Icloud keynote2
Icloud keynote2Icloud keynote2
Icloud keynote2
 
iCloud
iCloudiCloud
iCloud
 

Similar to Bonjour, iCloud

Rails and iOS with RestKit
Rails and iOS with RestKitRails and iOS with RestKit
Rails and iOS with RestKit
Andrew Culver
 

Similar to Bonjour, iCloud (20)

CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
CocoaHeads PDX 2014 01 23 : CoreData and iCloud Improvements iOS7 / OSX Maver...
 
Connecting to a REST API in iOS
Connecting to a REST API in iOSConnecting to a REST API in iOS
Connecting to a REST API in iOS
 
Simpler Core Data with RubyMotion
Simpler Core Data with RubyMotionSimpler Core Data with RubyMotion
Simpler Core Data with RubyMotion
 
Icinga 2009 at OSMC
Icinga 2009 at OSMCIcinga 2009 at OSMC
Icinga 2009 at OSMC
 
Concurrent networking - made easy
Concurrent networking - made easyConcurrent networking - made easy
Concurrent networking - made easy
 
03 objective-c session 3
03  objective-c session 303  objective-c session 3
03 objective-c session 3
 
Spring.io
Spring.ioSpring.io
Spring.io
 
OSMC 2009 | Icinga by Icinga Team
OSMC 2009 | Icinga by Icinga TeamOSMC 2009 | Icinga by Icinga Team
OSMC 2009 | Icinga by Icinga Team
 
Json within a relational database
Json within a relational databaseJson within a relational database
Json within a relational database
 
Introduction to MVC in iPhone Development
Introduction to MVC in iPhone DevelopmentIntroduction to MVC in iPhone Development
Introduction to MVC in iPhone Development
 
Datacon LA - MySQL without the SQL - Oh my!
Datacon LA - MySQL without the SQL - Oh my! Datacon LA - MySQL without the SQL - Oh my!
Datacon LA - MySQL without the SQL - Oh my!
 
MySQL Without the SQL -- Oh My!
MySQL Without the SQL -- Oh My!MySQL Without the SQL -- Oh My!
MySQL Without the SQL -- Oh My!
 
Discover the Power of the NoSQL + SQL with MySQL
Discover the Power of the NoSQL + SQL with MySQLDiscover the Power of the NoSQL + SQL with MySQL
Discover the Power of the NoSQL + SQL with MySQL
 
Discover The Power of NoSQL + MySQL with MySQL
Discover The Power of NoSQL + MySQL with MySQLDiscover The Power of NoSQL + MySQL with MySQL
Discover The Power of NoSQL + MySQL with MySQL
 
OpenCL Programming 101
OpenCL Programming 101OpenCL Programming 101
OpenCL Programming 101
 
第一次用Parse就深入淺出
第一次用Parse就深入淺出第一次用Parse就深入淺出
第一次用Parse就深入淺出
 
Open Source World June '21 -- JSON Within a Relational Database
Open Source World June '21 -- JSON Within a Relational DatabaseOpen Source World June '21 -- JSON Within a Relational Database
Open Source World June '21 -- JSON Within a Relational Database
 
MySQL Without the SQL - Oh My! August 2nd presentation at Mid Atlantic Develo...
MySQL Without the SQL - Oh My! August 2nd presentation at Mid Atlantic Develo...MySQL Without the SQL - Oh My! August 2nd presentation at Mid Atlantic Develo...
MySQL Without the SQL - Oh My! August 2nd presentation at Mid Atlantic Develo...
 
MySQL Without the SQL - Oh My! -> MySQL Document Store -- Confoo.CA 2019
MySQL Without the SQL - Oh My! -> MySQL Document Store -- Confoo.CA 2019MySQL Without the SQL - Oh My! -> MySQL Document Store -- Confoo.CA 2019
MySQL Without the SQL - Oh My! -> MySQL Document Store -- Confoo.CA 2019
 
Rails and iOS with RestKit
Rails and iOS with RestKitRails and iOS with RestKit
Rails and iOS with RestKit
 

More from Chris Adamson

More from Chris Adamson (20)

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

Recently uploaded

CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

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
  • 12. http://mattgemmell.com/2011/07/25/network-link- conditioner-in-lion/ 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