iOS Development
                 Lecture 2 - The practical stuff



Petr Dvořák
Partner & iOS Development Lead
@joshis_tweets
Outline
Outline
• Network Aware Applications
  • Connecting to the server
  • Processing data from the server
  • Working with UIWebView
Outline
• Using system dialogs
  • Picking a contact
  • Taking a photo
  • Composing an e-mail or SMS
  • Social networks
Outline
• Threading
  • NSThread
  • GCD (Grand Central Dispatch)
  • NSOperation
Network Aware Apps
Networking
• Three classes to make it work
 •   [NSURL URLWithString:@”http://google.com”];

 •   [NSURLRequest requestWithUrl:url];

 •   [NSURLConnection connectionWithRequest:request
                                   delegate:self]
Connection callbacks
// NSURLConnectionDataDelegate formal protocol since iOS 5

// HTTP response
- (void) connection:(NSURLConnection *)connection
 didReceiveResponse:(NSURLResponse *)response;


// Data chunk received
- (void) connection:(NSURLConnection *)connection
     didReceiveData:(NSData *)data;


// All done
- (void) connectionDidFinishLoading:(NSURLConnection *)conn;


// Problem with connection
- (void) connection:(NSURLConnection *)connection
   didFailWithError:(NSError *)error;
Processing JSON
• JSON-Framework
  • New BSD Licence
  • JSON parser and generator
  • http://stig.github.com/json-
    framework/
Processing XML
• TouchXML
  • Modified BSD Licence
  • DOM parser + XPath, XML
   Namespaces
 • https://github.com/TouchCode/
   TouchXML
System dialogs
System dialogs
• Allow performing usual tasks in
  a consistent manner
• Complete process handling
• Delegate based
MFMailComposeViewController

• System dialog for composing an
  e-mail message
• May be pre-filled with e-mail data
• Support for attachments
• + (BOOL) canSendMail;
MFMessageComposeViewController

 • System dialog for composing an
   SMS message
 • No MMS / attachments
 • May be pre-filled with message body
   and recipients (string array)
 • + (BOOL) canSendText;
UIImagePickerController
• System dialog for picking a photo
• Uses “sourceType” flag to determine
  source
 • camera, library, saved photos
• Check for camera before touching it
• Delegate based
Address Book
• Creating and searching contacts
• Allows manual access via C API
 •   ABAddressBookCreate

 •   ABAddressBookCopyArrayOfAllPeople

 •   ABAddressBookSave

• Contains predefined dialogs
ABPeoplePickerNavigationController

 • System dialog for picking a contact
 • Allows picking a contact or a contact
   property
ABPeoplePickerNavigationController *pp =
    [[ABPeoplePickerNavigationController alloc] init];
pp.peoplePickerDelegate = self;
[self presentModalViewController:pp
                        animated:YES];

//...

- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)p
      shouldContinueAfterSelectingPerson:(ABRecordRef)person
                                property:(ABPropertyID)property
                              identifier:(ABMultiValueIdentifier)identifier
{
    //...
}
ABNewPersonViewController
• System dialog for creating a contact
• May be pre-initialized
ABPersonViewController
• System dialog for displaying a contact
• Optional editing
Twitter API
• Native Twitter&Facebook
  support since iOS 6
• SocialFramework
• No need to reimplement
  authentication =>
 • Reasonably secure
Threading
Why threads?

• Slow operations must not block UI
  • Network operations
  • Computations
  • Filesystem operations
NSThread

• Low level thread abstraction
• Requires you to do all the
  synchronization manually
- (void) detachAsyncOperation {
    [NSThread detachNewThreadSelector:@selector(operation:)
                     toTarget:self
                     withObject:contextData];
}


- (void) operation:(id)contextData {
    @autorelease {
        // slow code here
        // ...
        [self performSelectorOnMainThread:@selector(updateUI:)
                               withObject:contextData
                            waitUntilDone:NO];
    }
}
GCD

• Working with NSThread is difficult
• GCD makes an abstraction above
  threads
• C API, functions/macros starting with
  “dispatch_” prefix
Dispatch Queue

• Queue of blocks to be performed
 •   FIFO, synchronized

• Reference-counted
 •   dispatch_queue_create ➞ dispatch_release

• One queue per use-case
dispatch_queue_t main_queue = dispatch_get_main_queue()
dispatch_queue_t network_queue = dispatch_get_global_queue(priority, 0);
// dispatch_queue_t network_queue2 =
//             dispatch_queue_create("eu.inmite.net", NULL);

dispatch_async(network_queue, ^ {
    // some slow code
    dispatch_async(main_queue, ^{
        // update UI
    });
    // dispatch_release(network_queue2);
});
Dispatch Semaphore

•   dispatch_semaphore_create
•   dispatch_semaphore_wait
•   dispatch_semaphore_signal
Dispatch After
int64_t delayInSeconds = 2.0;
dispatch_time_t popTime = dispatch_time(
    DISPATCH_TIME_NOW,
    delayInSeconds * NSEC_PER_SEC
);

dispatch_after(popTime, dispatch_get_main_queue(), ^{
       // executed on the main queue after delay
});
Singleton Pattern


  // within class Foo
  + (Foo*) getDefault {
      static dispatch_once_t pred;
      static Foo *inst;
      dispatch_once(&pred, ^ {
          inst = [[Foo alloc] init];
      });
      return inst;
  }
NSOperation
• Abstraction above “operation”
• Meant to be subclassed
 •   main - code to be executed

 •   start - start the operation

 •   cancel - set the cancel flag


• Operation priority
• Dependencies
 •   [op1 addDependency:op2];
NSInvocationOperation
• NSOperation subclass
• Operation based on target & selector

 [[NSInvocationOperation alloc] initWithTarget:target
                                      selector:selector
                                        object:context];
NSBlockOperation
• NSOperation subclass
• Operation based on block

 [NSBlockOperation blockOperationWithBlock:^{
       // some code...
 }];
NSOperationQueue
• NSOperations are not meant to be
  run directly
• NSOperationQueue runs the
  operations correctly
• Configurable number of concurrent
  operations
NSOperationQueue


 NSOperationQueue *queue = [NSOperationQueue mainQueue];
 // queue = [NSOperationQueue currentQueue];
 // queue = [[NSOperationQueue alloc] init];

 [queue addOperation:anOperation];
Threading summary
• UI must run on main thread
• Slow task must run on the separate
  thread
• Practically, the most convenient way
  is using GCD & blocks
Thank you
                   http://www.inmite.eu/talks



Petr Dvořák
Partner & iOS Development Lead
@joshis_tweets

MFF UK - Advanced iOS Topics

  • 1.
    iOS Development Lecture 2 - The practical stuff Petr Dvořák Partner & iOS Development Lead @joshis_tweets
  • 2.
  • 3.
    Outline • Network AwareApplications • Connecting to the server • Processing data from the server • Working with UIWebView
  • 4.
    Outline • Using systemdialogs • Picking a contact • Taking a photo • Composing an e-mail or SMS • Social networks
  • 5.
    Outline • Threading • NSThread • GCD (Grand Central Dispatch) • NSOperation
  • 6.
  • 7.
    Networking • Three classesto make it work • [NSURL URLWithString:@”http://google.com”]; • [NSURLRequest requestWithUrl:url]; • [NSURLConnection connectionWithRequest:request delegate:self]
  • 8.
    Connection callbacks // NSURLConnectionDataDelegateformal protocol since iOS 5 // HTTP response - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response; // Data chunk received - (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data; // All done - (void) connectionDidFinishLoading:(NSURLConnection *)conn; // Problem with connection - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
  • 9.
    Processing JSON • JSON-Framework • New BSD Licence • JSON parser and generator • http://stig.github.com/json- framework/
  • 10.
    Processing XML • TouchXML • Modified BSD Licence • DOM parser + XPath, XML Namespaces • https://github.com/TouchCode/ TouchXML
  • 11.
  • 12.
    System dialogs • Allowperforming usual tasks in a consistent manner • Complete process handling • Delegate based
  • 13.
    MFMailComposeViewController • System dialogfor composing an e-mail message • May be pre-filled with e-mail data • Support for attachments • + (BOOL) canSendMail;
  • 14.
    MFMessageComposeViewController • Systemdialog for composing an SMS message • No MMS / attachments • May be pre-filled with message body and recipients (string array) • + (BOOL) canSendText;
  • 15.
    UIImagePickerController • System dialogfor picking a photo • Uses “sourceType” flag to determine source • camera, library, saved photos • Check for camera before touching it • Delegate based
  • 16.
    Address Book • Creatingand searching contacts • Allows manual access via C API • ABAddressBookCreate • ABAddressBookCopyArrayOfAllPeople • ABAddressBookSave • Contains predefined dialogs
  • 17.
    ABPeoplePickerNavigationController • Systemdialog for picking a contact • Allows picking a contact or a contact property
  • 18.
    ABPeoplePickerNavigationController *pp = [[ABPeoplePickerNavigationController alloc] init]; pp.peoplePickerDelegate = self; [self presentModalViewController:pp animated:YES]; //... - (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)p shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier { //... }
  • 19.
    ABNewPersonViewController • System dialogfor creating a contact • May be pre-initialized ABPersonViewController • System dialog for displaying a contact • Optional editing
  • 20.
    Twitter API • NativeTwitter&Facebook support since iOS 6 • SocialFramework • No need to reimplement authentication => • Reasonably secure
  • 21.
  • 22.
    Why threads? • Slowoperations must not block UI • Network operations • Computations • Filesystem operations
  • 23.
    NSThread • Low levelthread abstraction • Requires you to do all the synchronization manually
  • 24.
    - (void) detachAsyncOperation{ [NSThread detachNewThreadSelector:@selector(operation:) toTarget:self withObject:contextData]; } - (void) operation:(id)contextData { @autorelease { // slow code here // ... [self performSelectorOnMainThread:@selector(updateUI:) withObject:contextData waitUntilDone:NO]; } }
  • 25.
    GCD • Working withNSThread is difficult • GCD makes an abstraction above threads • C API, functions/macros starting with “dispatch_” prefix
  • 26.
    Dispatch Queue • Queueof blocks to be performed • FIFO, synchronized • Reference-counted • dispatch_queue_create ➞ dispatch_release • One queue per use-case
  • 27.
    dispatch_queue_t main_queue =dispatch_get_main_queue() dispatch_queue_t network_queue = dispatch_get_global_queue(priority, 0); // dispatch_queue_t network_queue2 = // dispatch_queue_create("eu.inmite.net", NULL); dispatch_async(network_queue, ^ { // some slow code dispatch_async(main_queue, ^{ // update UI }); // dispatch_release(network_queue2); });
  • 28.
    Dispatch Semaphore • dispatch_semaphore_create • dispatch_semaphore_wait • dispatch_semaphore_signal
  • 29.
    Dispatch After int64_t delayInSeconds= 2.0; dispatch_time_t popTime = dispatch_time( DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC ); dispatch_after(popTime, dispatch_get_main_queue(), ^{ // executed on the main queue after delay });
  • 30.
    Singleton Pattern // within class Foo + (Foo*) getDefault { static dispatch_once_t pred; static Foo *inst; dispatch_once(&pred, ^ { inst = [[Foo alloc] init]; }); return inst; }
  • 31.
    NSOperation • Abstraction above“operation” • Meant to be subclassed • main - code to be executed • start - start the operation • cancel - set the cancel flag • Operation priority • Dependencies • [op1 addDependency:op2];
  • 32.
    NSInvocationOperation • NSOperation subclass •Operation based on target & selector [[NSInvocationOperation alloc] initWithTarget:target selector:selector object:context];
  • 33.
    NSBlockOperation • NSOperation subclass •Operation based on block [NSBlockOperation blockOperationWithBlock:^{ // some code... }];
  • 34.
    NSOperationQueue • NSOperations arenot meant to be run directly • NSOperationQueue runs the operations correctly • Configurable number of concurrent operations
  • 35.
    NSOperationQueue NSOperationQueue *queue= [NSOperationQueue mainQueue]; // queue = [NSOperationQueue currentQueue]; // queue = [[NSOperationQueue alloc] init]; [queue addOperation:anOperation];
  • 36.
    Threading summary • UImust run on main thread • Slow task must run on the separate thread • Practically, the most convenient way is using GCD & blocks
  • 37.
    Thank you http://www.inmite.eu/talks Petr Dvořák Partner & iOS Development Lead @joshis_tweets