MFF UK - Advanced iOS Topics
-
Upload
petr-dvorak -
Category
Technology
-
view
1.271 -
download
2
Transcript of MFF UK - Advanced iOS Topics
iOS DevelopmentLecture 2 - The practical stuff
Petr DvořákPartner & 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
• Modi#ed 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 ane-mail message
• May be pre-#lled with e-mail data
• Support for attachments
• + (BOOL) canSendMail;
MFMessageComposeViewController
• System dialog for composing anSMS message
• No MMS / attachments
• May be pre-#lled with message body and recipients (string array)
• + (BOOL) canSendText;
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
Address Book
• Creating and searching contacts
• Allows manual access via C API
• ABAddressBookCreate
• ABAddressBookCopyArrayOfAllPeople
• ABAddressBookSave
• Contains prede#ned 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_” pre#x
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 %ag
• 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
• Con#gurable 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 youhttp://www.inmite.eu/talks
Petr DvořákPartner & iOS Development Lead@joshis_tweets