Mobile devices are so useful because they can get on the net with their built-in wi-fi or cellular data radios. But how does this work? In iOS, we have a slew of networking APIs, each appropriate in different situations. From decades-old BSD sockets to the new-in-iOS-5 iCloud, there are a wide range of networking calls available to your app, and an equally wide range of semantics in how to use them. In this talk, we'll start with high-level abstractions like iCloud and other objects that can either load from or save to a URL, then progress down through the stack, grabbing arbitrary content from URLs, self-networking with Bonjour and Game Kit, and finally accessing the socket layer with CFNetwork and BSD sockets.
iCloud sample code at: http://dl.dropbox.com/u/12216224/conferences/codemash12/bonjour-icloud/CloudNotes.zip
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
10. Reachability callbacks
• Networks come and go; your app should
handle this
• SCNetworkReachabilitySetCallback()
MyNetworkReachabilityCallBack(
SCNetworkReachabilityRef target,
SCNetworkReachabilityFlags flags,
void *info
);
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
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
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
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