MFF UK - Advanced iOS Topics

37
iOS Development Lecture 2 - The practical stuPetr Dvořák Partner & iOS Development Lead @joshis_tweets

Transcript of MFF UK - Advanced iOS Topics

Page 1: MFF UK - Advanced iOS Topics

iOS DevelopmentLecture 2 - The practical stuff

Petr DvořákPartner & iOS Development Lead@joshis_tweets

Page 2: MFF UK - Advanced iOS Topics

Outline

Page 3: MFF UK - Advanced iOS Topics

Outline

• Network Aware Applications

• Connecting to the server

• Processing data from the server

• Working with UIWebView

Page 4: MFF UK - Advanced iOS Topics

Outline

• Using system dialogs

• Picking a contact

• Taking a photo

• Composing an e-mail or SMS

• Social networks

Page 5: MFF UK - Advanced iOS Topics

Outline

• Threading

• NSThread

• GCD (Grand Central Dispatch)

• NSOperation

Page 6: MFF UK - Advanced iOS Topics

Network Aware Apps

Page 7: MFF UK - Advanced iOS Topics

Networking• Three classes to make it work

• [NSURL URLWithString:@”http://google.com”];

• [NSURLRequest requestWithUrl:url];

• [NSURLConnection connectionWithRequest:request delegate:self]

Page 8: MFF UK - Advanced iOS Topics

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;

Page 9: MFF UK - Advanced iOS Topics

Processing JSON• JSON-Framework

• New BSD Licence

• JSON parser and generator

• http://stig.github.com/json-framework/

Page 10: MFF UK - Advanced iOS Topics

Processing XML• TouchXML

• Modi#ed BSD Licence

• DOM parser + XPath, XML Namespaces

• https://github.com/TouchCode/TouchXML

Page 11: MFF UK - Advanced iOS Topics

System dialogs

Page 12: MFF UK - Advanced iOS Topics

System dialogs

• Allow performing usual tasks in a consistent manner

• Complete process handling

• Delegate based

Page 13: MFF UK - Advanced iOS Topics

MFMailComposeViewController

• System dialog for composing ane-mail message

• May be pre-#lled with e-mail data

• Support for attachments

• + (BOOL) canSendMail;

Page 14: MFF UK - Advanced iOS Topics

MFMessageComposeViewController

• System dialog for composing anSMS message

• No MMS / attachments

• May be pre-#lled with message body and recipients (string array)

• + (BOOL) canSendText;

Page 15: MFF UK - Advanced iOS Topics

UIImagePickerController

• System dialog for picking a photo

• Uses “sourceType” %ag to determine source

• camera, library, saved photos

• Check for camera before touching it

• Delegate based

Page 16: MFF UK - Advanced iOS Topics

Address Book

• Creating and searching contacts

• Allows manual access via C API

• ABAddressBookCreate

• ABAddressBookCopyArrayOfAllPeople

• ABAddressBookSave

• Contains prede#ned dialogs

Page 17: MFF UK - Advanced iOS Topics

ABPeoplePickerNavigationController

• System dialog for picking a contact

• Allows picking a contact or a contact property

Page 18: MFF UK - Advanced iOS Topics

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{ //...}

Page 19: MFF UK - Advanced iOS Topics

ABNewPersonViewController

• System dialog for creating a contact

• May be pre-initialized

ABPersonViewController

• System dialog for displaying a contact

• Optional editing

Page 20: MFF UK - Advanced iOS Topics

Twitter API• Native Twitter&Facebook

support since iOS 6

• SocialFramework

• No need to reimplement authentication =>

• Reasonably secure

Page 21: MFF UK - Advanced iOS Topics

Threading

Page 22: MFF UK - Advanced iOS Topics

Why threads?

• Slow operations must not block UI

• Network operations

• Computations

• Filesystem operations

Page 23: MFF UK - Advanced iOS Topics

NSThread

• Low level thread abstraction

• Requires you to do all the synchronization manually

Page 24: MFF UK - Advanced iOS Topics

- (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]; }}

Page 25: MFF UK - Advanced iOS Topics

GCD

• Working with NSThread is difficult

• GCD makes an abstraction above threads

• C API, functions/macros starting with “dispatch_” pre#x

Page 26: MFF UK - Advanced iOS Topics

Dispatch Queue

• Queue of blocks to be performed

• FIFO, synchronized

• Reference-counted

• dispatch_queue_create ➞ dispatch_release

• One queue per use-case

Page 27: MFF UK - Advanced iOS Topics

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);});

Page 28: MFF UK - Advanced iOS Topics

Dispatch Semaphore

• dispatch_semaphore_create

• dispatch_semaphore_wait

• dispatch_semaphore_signal

Page 29: MFF UK - Advanced iOS Topics

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});

Page 30: MFF UK - Advanced iOS Topics

Singleton Pattern

// within class Foo

+ (Foo*) getDefault {

static dispatch_once_t pred;

static Foo *inst;

dispatch_once(&pred, ^ { inst = [[Foo alloc] init]; });

return inst;

}

Page 31: MFF UK - Advanced iOS Topics

NSOperation• Abstraction above “operation”

• Meant to be subclassed• main - code to be executed

• start - start the operation

• cancel - set the cancel %ag

• Operation priority

• Dependencies• [op1 addDependency:op2];

Page 32: MFF UK - Advanced iOS Topics

NSInvocationOperation• NSOperation subclass

• Operation based on target & selector

[[NSInvocationOperation alloc] initWithTarget:target

selector:selector

object:context];

Page 33: MFF UK - Advanced iOS Topics

NSBlockOperation• NSOperation subclass

• Operation based on block

[NSBlockOperation blockOperationWithBlock:^{

// some code...

}];

Page 34: MFF UK - Advanced iOS Topics

NSOperationQueue• NSOperations are not meant to be

run directly

• NSOperationQueue runs the operations correctly

• Con#gurable number of concurrent operations

Page 35: MFF UK - Advanced iOS Topics

NSOperationQueue

NSOperationQueue *queue = [NSOperationQueue mainQueue];

// queue = [NSOperationQueue currentQueue];

// queue = [[NSOperationQueue alloc] init];

[queue addOperation:anOperation];

Page 36: MFF UK - Advanced iOS Topics

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

Page 37: MFF UK - Advanced iOS Topics

Thank youhttp://www.inmite.eu/talks

Petr DvořákPartner & iOS Development Lead@joshis_tweets