Swift meetup22june2015
-
Upload
claire-townend-gee -
Category
Software
-
view
51 -
download
0
Transcript of Swift meetup22june2015
Swift LA22 June 2015
eHarmony
• Introduction• What You Might Have Missed at WWDC• Swift 2.0• Swift & Enterprise & eHarmony• Questions?
Agenda
“We came together in 2000 believing that with a mix of psychology and some cutting edge technology, we could create relationships that were happier, more fulfilling and enduring.With over 61 million registered users, we’ve successfully married more than 565,000 couples, and are responsible for nearly 5% of marriages in the US — that’s 438 people every day that say ‘I Do’ because of eHarmony.”
“Millions of people have used eHarmony’s Compatibility Matching System to find compatible long-term relationships. Today, an average of 438 eHarmony members marry every day in the United States as a result of being matched on the site.”
Who is eHarmony?
Currently, we maintain Desktop Web, Mobile Web, iOS and Android apps for our scientific matching service.
Our iOS App currently boasts:• 8 billion downloads• Best selling app• Biggest grossing app
The team has been busy!
The eHarmony App
• Dr. Gary Philipp – Sr. Manager, Mobile EngineeringGary has a PhD in Engineering and a Masters in Behavioral Science. He is the old
man of the group (programming Apple products for over 30 years) and his first computer was an Apple II.
• Chris Truman – iOS EngineerSelf taught iOS developer, born and raised in LA. Previously worked at Urbanspoon
and TripAdvisor. Currently mentoring students in Swift through the Thinkful & One Month Swift programs. Loves Dogs, Comic Books, and long walks on the beach.
• Premal Mistry – iOS EngineerPremal loves designing and developing apps for iOS and Android and has over 6
years of experience in Software Development. He has a Masters in Computer Science and is passionate about learning new technologies (Swift, Design Patterns, Animation, etc). During weekends, I love to watch movies, TV shows, hanging out with friends and Yelping various food places in LA.
• Heena Rastogi – Senior iOS EngineerHeena earned a Masters in Computer Science (Multimedia and Creative
Technologies) and has been developing iOS apps for the past 6 years. She loves being a part of development projects that are focused on creative and exciting technologies. Outside of coding, she enjoys reading, running on the beach and listening to electronic music.
The Team
• UIStackView• Rich Playgrounds• Slide Over & Split View & PiP Video• Universal Links• App Search & CoreSpotlight• SFSafariViewController• App Transport Security• App Thinning• Storyboard References• UI Testing• Metal & Games• TestFlight and Push Notifications
What You Might Have Missed at WWDC 2015
• Axis• Distribution• Spacing• Animatable
UIStackView
• Markdown• Multi-Pages• Embedded Resources
Rich Playgrounds
• Launch Screen Storyboard• Autolayout & Size Classes• Window vs Screen
Slide Over & Split View & PiP
• App Site Association• Similar to Android Default Intents
Universal Links
• Background Indexing• NSUserActivity• Web Markup• Meta Data
App Search & CoreSpotlight
• Separate process• Cookies & Keychain• Tint Color• Custom Activity Items
SFSafariViewController
• HTTPS is mandatory-ish• Info.plist disabling• Exception Domains
App Transport Security
• Asset Splitting - @1x, @2x, @3x• On Demand Resources• BitCode
App Thinning
• Split up Large Storyboards• Custom Unwind Segues
Storyboard References
• New Testing Bundle Type• Record a Script
UI Testing
• Core Animation• On the Mac• ReplayKit, GameplayKit, ModelKit
Metal & Games
• Tester Limit increased to 2000• Push Notifications Text Input• 4k Push Payload Limit Increase• Feedback Service will be deprecated in
2016
TestFlight & Push Notifications
• Checking API Availability• Synthesized Headers• Protocol Extension• Error Handling• And more…
What’s New in Swift 2.0
Apple always rolls out new API’s and classes throughout the year.
How do we check for API & Class availability?
Checking API Availability in Swift
The old way:if NSClassFromString("SFSafariViewControler") != nil { let eHAdviceVC = SFSafariViewController(URL: url, entersReaderIfAvailable: true) eHAdviceVC.delegate = self presentViewController(eHAdviceVC, animated: true, completion: nil) } else { let eHAdviceVC = eHAdviceViewController(URL: url); presentViewController(eHAdviceVC, animated: true, completion: nil)}
Checking API Availability in Swift
Checking API Availability in Swift
The new way:if #available(iOS 9, OS X 10.10, watchOS 2, *) {
let eHAdviceVC = SFSafariViewController(URL: url, entersReaderIfAvailable: true) eHAdviceVC.delegate = self presentViewController(eHAdviceVC, animated: true, completion: nil) } else { let eHAdviceVC = eHAdviceViewController(); presentViewController(eHAdviceVC, animated: true, completion: nil)}
Synthesized header files:
Xcode 7 scans through your code and produces virtual header files that summarize the exposed methods with none of the code
Documentation - Similar to Apple's own classes
How to generate synthesized headers in Xcode 7?Xcode 7, go to Navigate > Generated Interface.
Synthesized Headers
Synthesized Headersextension NSURLRequest: URLRequestConvertible { public var URLRequest: NSURLRequest}
func URLRequest(method: Method, URL: URLStringConvertible) -> NSURLRequest
/** Creates a request using the shared manager instance for the specified method, URL string, parameters, and parameter encoding.
:param: method The HTTP method. :param: URLString The URL string. :param: parameters The parameters. `nil` by default. :param: encoding The parameter encoding. `.URL` by default.
:returns: The created request.*/public func request(method: Method, URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request
/** Creates a request using the shared manager instance for the specified URL request.
If `startRequestsImmediately` is `true`, the request will have `resume()` called before being returned.
:param: URLRequest The URL request
:returns: The created request.*
Protocol Extensions
Protocols can be extended to provide method and property implementations to conforming types.
You can use protocol extensions to provide a default implementation to any method or property requirement of that protocol.
Protocol ExtensionsExample:
let ageOfEmployees: [Int?] = [30, 32, nil, 45, 50, 12, 8, 25, nil]
extension SequenceType where Generator.Element: OptionalType { var purify: [Self.Generator.Element.T] { return self.map { $0.optional }.filter { $0 != nil }.map { $0! } }}
let ageOfEmployees: [Int?] = [30, 32, nil, 45, 50, 12, 8, 25, nil]ageOfEmployees.purify
[30, 32, 45, 50, 12, 8, 25]
Error Handling
Example:func refreshActivityFeed() { let refreshToken = login() loadActivityFeed(refreshToken) updateUI()}
Error HandlingThe Old Way:func refreshActivityFeed() { let refreshToken:String? = login(username, error:&error) if (error != nil) { if let error = error { switch (error.code) { case ERROR_UNAUTHORIZED: showLoginVC() case ERROR_FORBIDDEN: showErrorAlert() case ERROR_NOT_FOUND: showLoginVC() default: showErrorAlert() } } } else { // Fetch the most recent activity feeds from the server // Parse and prepare data structure // Update UI loadActivityFeed(refreshToken!) updateUI() }}
The New Way:func refreshActivityFeed() { do { let refreshToken = try login(username) loadActivityFeed(refreshToken) updateUI() } catch (LoginError.ERROR_UNAUTHORIZED) { showLoginVC() } catch (LoginError.ERROR_FORBIDDEN) { showErrorAlert() } catch (LoginError.ERROR_NOT_FOUND) { showLoginVC() } catch { showErrorAlert() }}
Error Handling
Error HandlingRepresenting Errors
• ErrorType is a protocol in the Swift Standard Library
• Any type that conforms to ErrorType can be thrown and caught
• Can make your own types conform as well
• enum is great for groups of related errors
enum LoginError : ErrorType { case ERROR_UNAUTHORIZED case ERROR_FORBIDDEN case ERROR_NOT_FOUND case ERROR_NOT_ALLOWED case ErrorWithMessage(code: Int, message: String)}
Throwing Errors:enum VendingMachineError: ErrorType { case InvalidSelection case InsufficientFunds(required: Double) case OutOfStock}
func purchaseItemFromVendingMachine(item: VendingItem) throws -> Bool { if item.count() > 0 { // ..... return true } else { throw VendingMachineError.OutOfStock }}
Error Handling
Catching and Handling Errors:func refreshActivityFeed() { do { let refreshToken = try loginWithUserName(username) loadActivityFeed(refreshToken) updateUI() } catch (LoginError.ERROR_UNAUTHORIZED) { showLoginVC() } catch (LoginError.ERROR_FORBIDDEN) { showErrorAlert() } catch (LoginError.ERROR_NOT_FOUND) { showLoginVC() } catch { showErrorAlert() }}
Error Handling
Disabling Error Propagation:
try! loadConfiguration()
Error Handling
Specifying Cleanup Actions:func processFile(filename: String) throws { if exists(filename) {
do { let file = try open(filename) defer { close(file) }
while let line = try file.readline() { ... }
} catch {...
} }}
Error Handling
And More…Guard:func validateJSON() -> Bool { guard let name = person["name"] else { return false } ..... ..... return true}
• Designed to solve pyramid of doom problem• Extremely useful for early exit
Swift & Enterprise & eHarmony
• Why?• Bridging & Migration• eHarmony’s Plan to Tackle
• Simpler to read
• Type safety and hence code safety
• Interacts with Objective-C Runtime seamlessly
• Take advantage of Objective-C APIs and Cocoa design patterns
• Open Source - we gain flexibility and freedom
• Other platforms can also adopt Swift
Why?
3 important aspects of Swift / Objective-C compatibility:
• InteroperabilityAbility to interface between Swift and Objective-C in either direction
• Mix and MatchAllows you to create mixed-language apps containing both Swift and Objective-C files that can communicate with each other
• MigrationMigration from existing Objective-C code to Swift is made easy with interoperability and mix and match, making it possible to replace parts of your Objective-C apps with the latest Swift features
Bridging & Migration
3 New features introduced for Objective-C :
• Nullability for Objective-C
• Lightweight Generics
• Kind of
Bridging & Migration
Bridging & Migration
Objective-C
@interface SNGFeedView@property(nonatomic, readonly) UIView *photoView;@property(nonatomic, readonly, copy) NSArray *feedViews;- (UIView*) photoViewForFeed:(SSFeed) photoFeed;@end
Swift
class SNGFeedView { var photoView : UIView? var feedViews: [AnyObject]! func photoView(photoFeed:SSFeed) - > UIView}
Indicate whether Objective-C/C pointers can be nil
• Better communicate intent of APIs
• Allows improved static checking
• Improves usability of APIs in Swift
Nullability
Nullability Qualifiers
Nullability
Qualifier Usage Swift
nullable Pointer may be nil UIView?
nonnull nil is not a meaningful value
UIView
null_unspecified Neither nullable nor nonnull applies
UIView!
NOTE: Compiler does not change the way it generates code because of a non-null annotation.
Example:
NS_ASSUME_NONNULL_BEGIN
@interface SNGFeedView@property(nonatomic,readonly,nullable) UIView *photoView;@property(nonatomic, readonly,copy) NSArray *feedViews;-(UIView*) photoViewForFeed:(SSFeed) photoFeed;@end
NS_ASSUME_NONNULL_END
Audited regions make default assumptions about some pointers:• Single-level pointers are assumed to be nonnull• NSError** parameters are assumed to be nullable for
both levels• Only annotate the nullable or null_unspecified cases
Nullability
Allow collections to be parameterized by element type:
“An array of views” , “A dictionary mapping strings to images”
• Improve expressivity of APIs
• Make collections easier to use
• Enable better static type checking
Lightweight Generics
Objective–C@interface SNGFeedView@property(nonatomic)NSArray <UIView*> feedSubviews;@property(nonatomic,assign)BOOL filter;@end
Swiftclass SNGFeedView {var subviews: [UIView] { get }}
Lightweight Generics
• It tells compiler it’s object of some kind of of given type
extern __kindof NSApplication *NSApp; // NSApplication instanceNSObject *object = NSApp; // convert to super classMyApplication *myApp = NSApp; // implicit downcast subclassNSString *string = NSApp // Incorrect
• Much more useful than id, more type information in API contract
• Allows messaging subclass methods[NSApp praiseUser] // Invokes MyApplication method
KindOf Types
• Modernization of Objective-C
• Generating Bridging Headers
• Incremental Migration
eHarmony’s Plan to Tackle
Before you start:
• Create a Swift class for your corresponding Objective-C .m and .h
• Import relevant system frameworks
• Fill out an Objective-C bridging header if you need to access Objective-C code from the same app target in your Swift file
• To make your Swift class accessible and usable back in Objective-C, make it a descendant of an Objective-C class or mark it with the @objc attribute
Migration
As you work:
• Set up your Swift class by subclassing Objective-C classes, adopting Objective-C protocols, and more.
• See “Adopting Cocoa Design Patterns” for information on translating common design patterns.
• To translate your properties from Objective-C to Swift, read Properties in “The Swift Programming Language.”
• Declare simple macros as global constants, and translate complex macros into functions.
Migration
After you finish:
• Update import statements in your Objective-C code (to #import "ProductModuleName-Swift.h"), as described in “Importing Code from Within the Same App Target”
• Remove the original Objective-C .m file from the target by deselecting the target membership checkbox
• Update your code to use the Swift class name instead of the Objective-C name if you gave the Swift class a different name
Migration
Questions?