Академический Документы
Профессиональный Документы
Культура Документы
2015
Table of Contents
1. introduction
2. App Framework
i. Adopting new trackpad feature
ii. Advanced NSOperation
iii. Advance Touch Input in iOS
iv. Best Practices for Progress Reporting
v. Building Document Based App
vi. Cocoa Touch Best Practices
vii. Creating Complications with ClockKit
viii. Getting Started with Multitasking on iPad in iOS 9
ix. Introducing safari View Controller and WKWebView updates
x. Introducing the Contacts Framework
xi. Multitasking Essentials for Media-Based Apps on iPad in iOS 9
xii. Mysteries of Auto Layout, Part 1
xiii. Mysteries of Auto Layout, Part 2
xiv. New UIKit Support for International User Interfaces
xv. Optimizing Your App for Multitasking on iPad in iOS 9
xvi. Seamless linking to your app
xvii. WatchKit In-Depth, Part 1
xviii. WatchKit In-Depth, Part 2
xix. What's new in Cocoa
xx. What's new in Core Data
xxi. What's new in HealthKit
xxii. What's new in Internationalization
xxiii. What's new in Mapkit
xxiv. Whats New in UIKit Dynamics and Visual Effects
xxv. iOS Accessilibility
3. Design
4. Developer Tools
i. App Thinning in Xcode
ii. Building Better Apps with Value Types in Swift
iii. Improving your existing apps with Swift
iv. Optimizing Swift Performance
v. Swift and Objective-C interoperability
vi. Swift in Practice
vii. What's new in LLDB
5. Distribution
i. Getting the Most out of App Analytics
ii. What's new in Managing Apple Devices
iii. Whats New in iTunes Connect
iv. iTunes Connect: Development to Distribution
6. Featured
i. Introducing watchKit for watchOS2
ii. Platform of the union
iii. What's news in Cocoa Touch
iv. What's new in swift
v. What's New in Xcode
7. Graphics and Games
i. Going Social with ReplayKit and Game Center
2
WWDC 2015
8. Media
i. Safari Extensibility: Content Blocking and Shared Links
ii. What's new in Core Image
9. System Frameworks
i. Achieving All-Day Battery
ii. Apple Pay within apps
iii. Building Responsive and Efficient Apps with GCD
iv. CloudKit JS and Web Services
v. CloudKit Tips and Tricks
vi. Introducing Search APIs
vii. Introduction to Watch Connectivity
viii. Low Energy,High Performance:Compression and Accelerate
ix. Networking with NSURLSession
x. Privacy And Your App
xi. Security and Your Apps
xii. Whats New in CloudKit
xiii. What's New in Core Location
xiv. What's new in Core Motion
xv. What's new in Network extension and VPN
xvi. What's New in Notifications
3
WWDC 2015
UIColor.redColor()
introduction 4
WWDC 2015
rename file
quicklook
dictionary
NSTableViewRowAction
AcceleratorButton / MultiLevelAcceleratorButton
doubleValue for continuous range of value maxAcceleratorLevel for discerte levels of values
quickTime
Map NSSegmentSwitchTracking.MomentaryAccelerator
Force click on the control and scrolling the images faster. The data will come with a rate.
EventTypePressure
EventTypeMaskPressure
pressureChangeWithEvent
phase
stage
1 - click
2 - force click
0 - gesture release
pressure will be given when move becomes click and it drops to zero when hit click threshold (stage 1). After hit click
thresholds, the pressure will be increased from zero and hit thresholds for force click (stage 2). The pressure drops to zero
@protocol NSSpringLoadingDestination
//either one
func springLoadingEntered(NSDraggingInfo) -> NSStringLoadingOptions
@optional
func springLocalingActivated(Bool, draggingInfo: NSDraggingInfo)
func springLoadingHightlightChanged(NSDraggingInfo)
API Level 3
NSPRessureConfiguration to config trackpad behavior
[Advanced NSOperation]
NSOperation and NSOperationQueue are one of the important technology that builts on top of GCD. It is object-orientated and
In this session, the speaker tells the audiences that how to wrap the normal code pattern in to NSOperation suclasses and
operate them in a safe and dependency networks.
Advanced NSOperation 7
WWDC 2015
Coalesced Touches
120Hz Touch Scan for iPad Air 2 which means double touch events captured.
getting coaleascedTouches..
Touch Predication
Documentation of NSProgress
class NSProgress {
var totalUnitCount: Int64 //total work units
var completedUnitCount: Int64 //total work units completed
var fractionCompleted: Double { get } //computed property
var indeterminate: Bool { get } // return true if totalUnitCount < 0 or completedUnitCount < 0, useful when the total work unit is
var localizedDescription: String!
var localizedAdditionalDescription: String!
var kind: NSProgressKind
}
Localization
currently only setting kind as NSProgressKindFile to change the localizedDescriptions and
localizedAdditionalDescription
Responsibilities
For Creator
updating totalUnitCount
kind
userInfo for show different descriptions
completedUnitCount
For Clients
Composition
Composition of progress is needed when not tracking single progress but many progress
Use a parent progress that allows childs' progress to report back via pendingUnitCount
Implicit Composition
Explicit
Cancel
User Interface
NSProgress properties are key value observable
//somewhere in code
progress.addObserver(self, forKeyPath: "fractionCompleted", options: [], context: &observationContext)
Best Practices
Dont use fractionCompleted to determine completion
It is a float
Use completedUnitCount >= totalUnitCount (unless indetermineate or zero)
NSProgress can not be reused
make a new instance if additional progress
standalone
manages a list of documents
presents to user to edit etc.
Document browser
list doc in a manageful way
use thumbnails to preview the doc
show external doc like doc in iCloud
show recently accessed documents
Discovering document
NSFileManager only list the local doc, not for doc on iCloud or doc in other apps
NSMetadataQuery combines all available including local ,remote and external doc from other apps. This populate the
notification to inform hosting app for getting remote doc and any updates to the doc.
Recent List contains the document of user just worked on. Storing NSURL is not robust as the doc may be moved. Use
security scoped bookmarks as a pointer to the doc
Document Assess
NSFileCoordination for read/write lock NSFilePresenter to receive the updates whenever the document has been modified
Use background queue to create new doc as coordinated operations can block
Reading
Strongly suggested to use UIDocument to read and write, invoke loadFromContents() in background thread and completion
on main queue
in iOS 9
Writing
if providing custom thumbnails, make sure to thread-safety classes to create the images. UIViews are not thread-safe. Use
Core graphic suggested.
in iOS 8, the doc from other apps are copies. Presenting multiple copies to user is confusing.
in iOS 9, the doc may be directly reference to the another app documents as known as Open in place via
UIDocumentMenuViewController and UIDocument
func application(app: UIApplication, openUrl url: NSURL, options: [String: AnyObject]) -> Bool {
guard let shouldOpenInPlace = options[UIApplicationOpenURLOptionsOpenInPlaceKey] as? Bool else {
return false
}
//use the external url
let newURL = shouldOpenInPlace ? url : copyFileToContain(url)
documentBrowser.openDocumentAtURL(newURL)
return true
}
Goal
Perforamce
User Experience
Future proof
Leverage Framework
reduce maintainance costs
get improvement for free
focus time on make app special
System Versioning? target two major recent iOS version
Include version fallbacks
if systemVersion == 9.0 (wrong)
if available(9.0, *)
App Lifecycle
launch quickly!
applicationDidFinishLaunching return quickly!
Getting started
There will be new extension point for watch app in Xcode 7
Modular Small
Modular Large
Utilitarian Small
Utilitarian Large
Circular Small
The layout of UI is defined. Third-party developers are required to fill the content.
Important Classes
CLKImageProvider
//Initialize imageProvider
let imageProvider = CLKImageProvider(backgroundImage: bgImage,
backgroundColor: aColor,
foregroundImage: fgImage,
foregroundColor: CLKImageProviderForegroundColor.White)
CLKTextProvider
Other provider
CKComplicationTemplate
CLKImageProvider
CLKTextProvider ( can be multiple as families available)
TimeLine
As suggested before, in WatchOS 2, the users of watch can use "Time Travel" to view the past events like stocks or future
events like the calendar events and predicted weather data. There is critical to design a reasonable timeline so that the
users would not get confused.
CLKComplicationTimelineEntry
CLKComplicationTimelineEntry contains the timestamp and CKComplicationTemplate for represent a event in a timeline for
complication display
CLKComplicationDataSource is required data source for third party developer to implement all required protocol methods.
//Timeline start
func getTimelineStartDateForComplication(_ complication: CLKComplication,
withHandler handler: (NSDate?) -> Void)
//Timeline end
func getTimelineEndDateForComplication(_ complication: CLKComplication,
withHandler handler: (NSDate?) -> Void)
Related Sesssion: Multitasking Esstials for Media-based Apps on iPad in iOS 9, Optimizing Your App for Multitasking in iOS
Split View
Adaptivity
Existing app
```UITableView.cellLayoutMarginsFollowReadableWidth
Orientations
//not apply for multitasking as you may be much rooms in different direction
if UIInterfaceOrientationIsLandscape(interfaceOrientation) {
}
//encourage
if view.bounds.size.width > view.bounds.size.height {
}
//encourage
if traitCopllection.horizontalSizeClass == .Regular
}
in iOS 9 no need to set frame on window as iOS 9 figure out for you so it is okay to initial UIWindow without frame
Popover To handle popover arrow pointing to right position, these below are suggested.
popoverPresentationController.barButtonItem = sender
OR
popoverPresentationController.sourceView = button
popoverPresentationController.sourceRect = button.bounds
UIKeyboardWillShowNotification
UIKeyboardDidShowNotification
UIKeyboardWillHideNotification
UIKeyboardDidHideNotification
UIKeyboardWillChangeFrameNotification
UIKeyboardDidChangeFrameNotification
Best Practices
Strategies
2. Auto Layout
Related Session Mysteries of Auto Layout, Part 1 and Part 2
use margin and guide provided by system to have readable content regardless size classes changes
1. Xcode Support
5: High-level API
6: SplitViewController
Demo Project:AdaptivePhotos
Guidelines
Pro :
fast to setup
Cons:
var customUserAgent:String?
Classes
CNContact
CNMutableContact
A object that represented a contact in the contact book and the properties are mutable. Used in adding and update
contacts.
CNLabeledValue
CNSaveRequest
Can be cache multiple actions before executing. be aware of CNMutableContact not changing when writing into Contacts
Operations
Create contact
//Create contact
import Contacts
// create mutable for adding to the contact
let contact = CNMutableContact()
contact.imageData = // profile picture as NSData
contact.givenName = "John"
contact.familyName = "Appleseed"
contact.phoneNumbers = [CNLabeledValue(
label: CNLabelPhoneNumberiPhone,
value: CNPhoneNumber(stringValue: "(408) 555-0126"))]
try store.executeSaveRequest(saveRequest)
Updating A contact
Availbility check
Contact UI
CNContactPickerViewController and CNContactViewController will replace address book ui framework
CNContactPickerViewController
May return partial contacts (only the names but not the phone numbers)
Support mult-selection
predicateForSelectionOfContact to indicate Which contacts are returned when tapped, others push the detail card
predicateForSelectionOfProperty to indicate Which properties are returned when tapped, others perform the default action
based on CNContactProperty
Coherence between predicates and delegate methods as it does not make sense to filter the properties that you dont
want to get deleget methods
CNContactViewController
viewing contacts
Related session : Introducing AVKit in iOS 9 WWDC14 , Mastering modern media playback
MPMoviePlayerController
MPMoviePlayerViewController
Replaced by AVPlayerViewController
AVKit
AVPlayerViewController
Webkit
WKWebView supports background modes
WKWebConfiguarion to config allowsPictureinPicture default is yes
Best Practices
iPad is now have many foreground apps
full screen to serve only primary app
slide over will deactivite the primary and show secondary app temporary
split view to show 2 apps on a screen
PiP treats as background media
How to handle different situations for shared resources like audio, video and camera
Audio
Use one configuration
Only activate session when audio is first needed
Use Ambient category for game and sound effect and it is not interrupt the audio player underlying
use secondaryAudioShouldBeSilencedHint to check if secondary audio shuld be silenced
Related session Whats New in Core Audio in WWDC 2014
Audio Session Programming Guide on developer.apple.com/iOS
Video
use different variant of videos (high-res for full screen and low-Res for PiP)
Camera
One app can use camera
Availability can charge at any time.
UIRequiresFullscreen = YES if requires whole screen as the camera view finder
UIImagePickerController
AVCaptureSession
Observe AVCaptureSessionWasInterruptedNotification for interruption
AVCaptureSessionInterruptionReasonKey would give
UIStackView
A powerful UIKit component to build up a complex layout without forgiving the maintainability. UIStackView is also able to
nested. Hiding the views inside the stackView will make other subviews taking views room.
Changing Constraints
Prior to iOS 9, for any referenced constraints, we have to remove and re-add the constraints to certain views in order to
make these effective or not. In iOS 9, there are activate and deactivate for the constraint to take or not into account
when layout engine performs layouting.
View Sizing
Use Constraints to define the size of a view Overriding intrinsicContentSize for
UITableViewCell
Ambiguity
Not enough constraints to define the size or position of the view
Equal, non-required priorities
@"V:|-[image]-[caption](==image@751)]-1" to set the constraints' priorities
set above or below of the priorities as system uses some priorities as well
Content Priorities
Content Hugging (Hugging priorities hug content)
Alignment
use firstBaseLine and lastBaseline to align the first and last of line of text of base lines
use leading/trailing instead of left/right to help in localization as some of language are from right to left
Alignment Rects
Related Session
Constraints change
Activating or deactivating
Setting the constant or priority
Adding or removing views
set translatesAutoresizingMaskIntoConstraints to false for programmatically created views in order to flag the engine to not
create constraints for autoresizing masks
iOS 9 new anchor property to make the code more readable view.topAnchor.constraintEqualToAnchor(view.topAnchor,
costant:10) view.leadingAnchor.constraintEqualToAnchor(view.leadingAnchor, costant:10)
Ambiguous Layouts
(lldb) [view exerciseAmbiguityInLayout] for simulator running Ambiguous Layouts and (lldb) c to resume the
process
Start the debug logs from the bottom
Related Session
edit scheme > application language > right to left > pseduoLanguage to try
edit > add localization
edit > export for localization XLIFF
edit > import localization
Auto Layout
Use visual format or storyboard will flip leading and trailing constraints
Animation
Gesture recognizers
no change
Demo
override gestureRecogizerShouldBegin to check if the gesture recognizers we wanted , if not we return false,
Exception
Not All UI flip .Unspecified Affect auto-layout leading and trailing UISemanticContentAttribute.PlayBack and
UISemantticContentAttribute.Spartial
Best Practices
Exception on UIImage
func imageFlippedForRightToLeftLayoutDirection() -> UIImage flips images in RTL context without consideration of the
current context
applies to UIImageView
arrows
Chevrons
Some UI icons that match layout flows
Demo
Keep it small
may change based on context
Keep it bounded in terms of memory
CPU Management
Memory Warnings
Occured when
-[UIApplicationDelegate applicationDidReceiveMemoryWarning:]
-[UiViewController didReceiveMemoryWarning]
UIApplicationDidReceiveMemoryWarningNotification
DISPATCH_SOURCE_TYPE_MEMORYPRESSURE
NSCache
NSDictionary-like
Used for objects that can be regenerated on demand
Trims under memory pressure
Trims for application lifecycle change
NOT ON DISK
Absolutely essential
Expensive to generate
Can be pre-computed
Static once generated
* Data in a file can be "memory mapped" (not caching the whole file in the memory but a pointer to a location of the file location)
* memory and file content must be match exactly so it is useful for read-only data
* Data can be removed and reload when needed
This video introduces universal links to the apps when they tap links on the websites.
Demo (WWDC app) tapping website links -> native app detail page
http/https scheme
domain
path or path prefix
above not match -> safari
{
"applinks": {
"apps": [],
"details": {
"9JA89QQLNQ.com.apple.wwdc": {
"paths":[ "/wwdc/news/,
"/videos/wwdc/2015/*"]
}
}
}
}
openssl smime \
-sign \
-nodetach \
- in "unsigned.json"
- out "apple-app-site-association"
available in iOS 8
var webpageURL:NSURL ?
use NSURLComponent
Best practice
Validate input
fail gracefully (show a alert to inform user etc.)
send data over HTTPS
"applinks": {
"apps": [],
"details": {
"9JA89QQLNQ.com.apple.wwdc": {
"paths":[ "/wwdc/news/,
"/videos/wwdc/2015/*"]
}
}
}
"webcredentials" : {
"apps" : [ "a1234567".com.example.AppName"]
}
}
};
Architecture
in Watch OS 2, iPhone is no longer execute the watch app and watchKit Extension. Instead the watch app runs on the
watch
4 roles :
Application WKInterfaceController
Glance WKInterfaceController
Notification WKUserNotificationInterfaceController
Complication CLKComplicationDataSource
WKInterfaceController handles:
Interface properties
Menu Handling ( force touch menu)
Controller navigation and paging
Controller model presentation
Alert and action sheets
System UI - text input,video, audio
Setting image
Local data
Similar to iOS app local storage structure, document directory and caches directory are available for storing data.
Beware caches directory can be wiped out by system for reclaiming spaces. Document directory is purgeable but it will not
restored from backup.
Media
Transferring data
NSURLSession
Background upload and downloads
extension may not running
downloaded files must by copied
WatchConnectivity
Watch <-> Phone communication
Share data
Transfer files
Talk to each side
Related Session:Introducing Watch Connectivity
Migration
WatchOS 1
iOS SDK and platform
Runs on iPhone
Share framework with iOS
image caching
openParentApplication()
WatchOS 2
dedicated OS and some specific frameworks
Runs on Watch
more options on caching
Watch Connectivity for two way communication
Independent Operation
more layout and animations available
digital crown
New on WatchOS 2
Extension delegate
complication datasource
WKExtensionDelegate
```applicationDidBecomeActive
```handleUserActivity
OS 1 on root WKInterfaceController
OS 2 on WKExtensionDelegate
in coming WatchOS 2
var rootInterfaceController: WKInterfaceController will be available and can be called upon receiving handoff
//WKExtensionDelegate
func handleUserActivity(userInfo: [NSObject: AnyObject]) {
let rootController = WKExtension.sharedExtension.rootInterfaceController
rootController.popToRootController()
rootController.performActionsForUserActivity(userInfo)
}
`
Open URL
Phone (tel://)
SMS (sms://)
PassKit
Notification
iPhone is locked
Apple Watch is on wrist and unlocked
Notification Actions
and
Enhancement
Alert
func presentAlertC ontrollerWithTitle(title: String?, message: String?, preferredStyle: WKAlertControllerStyle, action:
[WKAlertAction])
Digital Crown
in the native apps, digital crown can control lists, pickers and volume
in WatchOS 2, WKInterfacePicker can be used accompanying with digital crown. There are 3 styles :
list style:
Stack style:
Sequence style:
Coordinating images
// WKImage can be initialized with local asset, remote with imageData: or draw with Core Image
progressInterfaceGroup.setBackgroundImage(progressImages)
once it set up , picker will assign the background image according to current selected index.
make sure picker item generates very fast as the list can scroll though many items in a short time.
Media Playback
1. load the asset from bundle and retrieve the url
2. setup options like WKMediaPlayerControllerOptionsAutoplayKey: ,
WKMediaPlayerControllerOptionsStartTimeKey: , WKMediaPlayerControllerOptionsVideoGravityKey: (aspect ratio)
3. and present the media player controller with url and options. provide handlers for checking if the media has played to
end, the finished time and error if any
WKInterfaceMovie is also provided if the player required to embed in other controllers. Movie remote url, the poster(the
thumnnail image to preview) and the video gravity ( the aspect ratio)
func setupMovie() {
//movie pointer set up via storyboard
movie.setMovieURL(url)
movie.setVideoGravity(.ResizeAspectFill)
movie.setPosterImage(poster)
}
Recommended formats
Long-form audio
Audio Recoding
call the following to get recording
Security
Store the data securely with locks/unlock mode
No iCloud Keychain
Swiftification
Nullability
null_resettable property can be set to nil but would not return nil (e.g. setting nil for default values)
use NS_ASSUME_NONNULL_BEGIN and NS_ASSUME_NONNULL_END for surrounding any never nil values
In general, nil is not valid value. NSString , NSArray , NSDictionary properties are rarely nil as using emptyness to
express. @"", @{} , @[]
Document the API that accepts or return nil on what nil means
e.g.
Generics
NSArray
NSDictionary
NSSet
NSOrderedSet
NSHashTable
NSMapTable
NSCache
NSEnumerator
kindof
and we retrieve an button from the subviews UIButton *button = myView.subviews[0] resulting an compiler warning as
UIButton is not the UIView.
having __kindof such that the collection accepts the generic classes and subclasses
Error Handling
translate to swift as
do {
try data.writeToURL(url, options:[])
} catch {
presentError(error as NSError)
}
out of bounds
Assertion failed
Names cleanup
typedef enum {
NSLeftTextAlignment,
...
} NSTextAlignment
becomes
typedef enum {
NSTextAlignmentLeft,
...
} NSTextAlignment
AppKit
Force Touch
Full Screen
Auto Layout
NSStackView or UIStackView
NSLayoutAnchor
NSLayoutGuide
Related Session : Mysteries of Auto Layout, Part 1 / Mysteries of Auto Layout, Part 2/ Improving the Full Screen Window
Experience
NSCollectionView
Text
NSTextField.maximumNumberOfLines
//allows the text becomes tighten before truncating
NSTextField.allowsDefaultTighteningForTruncation
Visual Atomicity
Foundation
Release notes for WWDC seed on OSX 10.11 and iOS 9
NSUndoManager
block-based undo
Sample code :
class ColorfulShape {
var undoManager : NSUndoManager?
var color = UIColor.blackColor() {
didSet {
undoManager?.registerUndoWithTarget(self) { target in
//old Value infer to type of UIColor
target.color = oldValue
}
}
}
}
NSProgress
protocol NSProgressReporting {
var progress: NSProgress { get }
}
NSNotificationCenter
NSPersonNameComponentsFormatter
NSString
observe the termal state change to lower CPU/ Memory/ GPU/ File IO using as necessary
Documentation of Thermal State
Core Data
unique constraints
Batch Deletion
other API enhancement
More
Core data handles multi-writing conflicts ,migration and persistent store vs. in-memory
New API
var haspersistentChangedValues: Bool { get } in NSManagedObject marks the object are dirty and prevent false positive
refreshAllObjects() for
We often need to remove the underlying database and create a new one for latest data. By doing so, that leaves many
issues such as corrupting the files and bad access to the live connections
if the destination does not exists, this will do a copy to the destination
Remove duplication
In Xcode 7, we can define what property of a model can be used as unique identifier.
Objection deletion
For current situation, if we need to delete some objects, we have to do the following 4 steps
NSBatchDeleteRequest is new api for us to not to pre-fetching the objects with focus on deleting
on one entiy,
one or more stores and
supporting predicates with sort descriptors and offsets.
returns
Models Change
we often update the models as app versions advance. Migration is needed to perform for differnt versions
Problem
in iOS 9
limitation
API Changes
nullability in API
__kindof
no need to update the header for adding new properties. Instead, editing Subclass+NSMAngedProperties.h or
Subclass+NSMangedProperties.swift for adding those new properties.
Related session: What's new in Core Data on iOS WWDC 2011 or NSManagedObjectContext Documentation
Performance
Use instrutment to measure the performance and find the data that should not prefetch
then use EXPLAIN QUERY PLAN [sql] to see the steps of the execution of sql
Change of HKObject
source of HKObject had been removed.
Added sourceRevision for storing sourceRevision and source with that object
Added new device property for storing related health devices information. use class function localDevice() for getting
the current device's information.
Deletion of HKObject
deleteObjects is added for deleting multiple HKObject
HKAnchoredObjectQuery for query all sample with predicate provided. The result also includes delete objects for developers
Background delivery invoke enableBackgroundDeliveryForType of HKHealthStore for sending info to third parties app.
Updating
use updateHandler of HKAnchoredObjectQuery to be informed whenever there are updates.
HealthKit in WatchOS
Same API
Assess to activity and workout data
New workout api
data syncs to companion device
Steps:
1. Request authorization for workout data types (like walking and running)
2. Start the HKWorkoutSession
3. Retrieve streamed samples from HKAnchoredObjectQuery
4. Save the HKWorkout and related sample
Localization
preferred language
if the app is not support the language, fall to second until the app support
In previous WWDC , localizing with xcode 6 that introduce XLIFF files that allows external translators to provide translations
without developers worrying about the format.
introduction
Language Ordering
sometimes it does not makes for foreign speaker to understand our language ordering
NSBundle.mainBundle().imageForResource("stopSign")
NSBundle.mainBundle().pathForSoundResource("greeting")
NSBundle.mainBundle().URLForResource("help", withExtension: "pdf")
Every language has different style for quality of one or more. Different rules becomes a issues and requires specific logics
to handle. iOS provides the stringsdict file for handling this kind of problem.
Variable Width
in iOS 9, we can set different strings for displaying in different device widths without using autolayout.
<key>Welcome</key>
<dict>
<key>NSStringVariableWidthRuleType</key>
<dict>
<key>20</key>
<!-- show "hi" in iPod Touch>
<string>Hi</string>
<key>25</key>
<!-- show "welcome" in iPhone>
<string>Welcome</string>
<!-- show "Welcome to the store!" in iPad>
<key>50</key>
<string>Welcome to the store!</string>
</dict>
</dict>
Formatting
Number format
in English , we use "." as showing decimal places. In German, the dot is use to separate the thousands. In order to handle
this,
Date Format
let df = NSDateFormatter()
df.dateStyle = .ShortStyle
df.timeStyle = .ShortStyle
//this will print suitable format for different language.
print(df.stringFromDate(NSDate())
//available in iOS 8
df.setLocalizedDateFormatFromTemplate("yyyyMMddjjmmss")
Weight Format
for example we have to show weight of 6 pounds to Italian weight unit. We don't know the metric of Italian so we have to
find out and do the convert on our own. Instead, we can use NSMassFormatter to format the unit and the number correctly.
Name Format
NSPersonNameComponents and NSPersonNameComponentsFormatter are useful classes when we need to format the names
components.givenName = "Grace"
components.middleName = "Murray"
components.familyName = "Hopper"
//Russian
let components = NSPersonNameComponents()
components.givenName = ""
components.middleName = ""
components.familyName = ""
//set up the formatter
let formatter = NSPersonNameComponentsFormatter()
formatter.style = .Short
formatter.stringFromPersonNameComponents(components)
Handling Text
when we do enumeration on string that contains emoji, this may gives unexpected result as there are multiple characters to
compose the emoji.
Case change
sometimes we change the cases of the string. The capped letter might not to reasonable for non-english speakers.
we should use:
Searching text
Transliteration
Layout
Full suport for right to left language
Dynamic Type
Use auto-layout and double-length presuo-language to try
side note : do not hard code the tableViewCell height as different languages requiring diff. heights for show the text
Related session : New UIKit Support for International User Interfaces WWDC 2015
Enhancement on API
Callout customization
New detailCalloutAccessoryView for support auto-layout or stackview as complex layout inside of callout
Map customization
Timezone support
CLGeocoder
MKLocalSearch
Swift support
WatchKit Support
Traffic
MKDirectionsTransportType for selecting transport type
ETA Request
}
}
//opening native maps for getting transit guides
func openInMapsTransit(coord:CLLocationCoordinate2D) {
var placemark = MKPlacemark(coordinate:coord, addressDictionary: nil)
var mapItem = MKMapItem(placemark: placemark)
let launchOptions = [MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeTransit]
mapItem.openInMapsWithLaunchOptions(launchOptions)
}
Flyover
New Map Type: .SatelliteFlyover , .HybridFlyover
MKOverlay
UIDynamicAnimator to Provide the overall context for animation and keep track of behaviors
UIKit Dynamics
Support for non-rectangular collision bounds
Path must be
Convex
Counter-clockwise wound
Non-self intersecting
UIDynamicItemGroup
Makes multiple dynamic items behave as one
Preserves the individual collision bounds
Dynamic items in a group must not be added to behaviors individually
A group cannot contain other groups
Concave or other complex shapes are possible
UIFieldBehaviormodels vector force fields
add to a region of the view
The field is evaluated at each point within the region
Resulting forces are applied by the animator
UIGravityBehavior is a field already!
Simplified physics, well-tuned for performance; but not for complex animations
UIDynamicItemBehavior
Customize physical properties
Applied to one or more items
var elasticity: CGFloat
var friction: CGFloat
var density: CGFloat
var resistance: CGFloat
var angularResistance: CGFloat
New var charge: CGFloat
New var anchored: Bool
UISnapBehavior
Snap a view in place
Customizable damping
Customizable snapPoint
UIAttachmentBehavior
New rope like attachment
debugAnimationSpeed to speed up or slow down the animation (it still counts so probabaly use 1x)
Visual Effects
UIVibrancyEffect
To create the content that transparent to the blur and show underneath background
Animation to the bounds of UIVisualEffectView Animation to the effect of UIVisualEffectView (from style of light to dark )
UIView.snapshotViewAfterScreenUpdates(afterUpdates:)
UIView.drawViewHierarchyInRect(rect:, afterScreenUpdates:)
UIScreen.snapshotViewAfterScreenUpdates()
dynamicsView.translatesAutoresizingMaskIntoConstraints = true
innerView.leadingAnchor.constraintEqualToAnchor(dynamicsView.leadingAnchor)
Custom UIDynamicItem
Subclass NSObject
Conform to UIDynamicItem
Provide .bounds
Update constraints when .center and .transform change
iOS Accessilibility
UIAccessilibility is the framework to provide bridge for iOS system and the app.
the below six variables that voice over query to the ui elements. All system-provided control are adopted and can be
overrided to fits better cases.
exteions NSObject {
//is accessible or not
var isAccessibilityElement: Bool
//the "text" of the button or label
var accessibilityLabel: String?
//additional desciption for this control
var accessibilityHint: String?
//used in sliders or some UI perform continuous values changing
var accessibilityValue: String?
// used for custom control. categorize the control
var accessibilityTraits: UIAccessibilityTraits
// the region that being detected
var accessiblilityFrame: CGRect
}
Use Accessibility inspector to check if there are any missing VO in the elements
Use UIAccessibilityElements for additioal accessbility elements for the custom controls in the app and add them to the
controllers.
New in iOS 9 , we can receive what element is being focused and perform required actions via
UIAccessibilityElementFocusedNotification
iOS Accessilibility 88
WWDC 2015
App Slicing
Slicing the app into different pieces and the suitable pieces will be downloaded according to the devices.
On Demand Resources
Based on the app flow, some resources can be downloaded afterwards like being purchasing via IAP or beating some
game levels. ODR (On Demand Resources) helps the developers to define what resources can be downloaded in later time
and removed the resource when the resource no longer needed.
Asset Slicing
Must use asset catalog for Asset Slicing
Device Traits
Graphics capabilities
Metal GPUFamily1
Metal GPUFamily2
Memory Level
1GB
2GB
Sprite Atlases ties full SpiriteKit integration. Auto-gen of SKTextureAtlases for image asset. Thinned appropriately.
Asset Organization
Workflow
Create
Export image set and data sets from existing asset pipelines
Format : XCAsset Source Artifact (Simple format strcture and JSON markup)
Build
Xcode Build and Run automatically thins resources for the active run destination. Supported for all simulator and device run
destinations.
Distribute
For enterprise-build, IPA-exporting will have options to export one app for all devices or for certain devices.
Make sure to tick includes manifest for over-the-air installations for generating the plist files that redirecting devices to the
thinned IPA.
This session provides a glance on what the value types are, explain why these types are important to Swift and how these
types solve the problems in better way.
Simply add a new swift file and Xcode will add the header file for the first time.
Adding Swift extension to extend existing Obj-c classes and enjoy benefits of Swift.
Availability Check
use #available(iOS 8.3, *) to have compile-time safety of APIs might not available in previous version s of system. A
map to mapping the multiple rows selections to the underlying data models
Using struct promotes value semantics which access the values inside of struct directly.
What if a struct has some referenced objects? Using a wrapping class to prevent copying of each referenced property.
Generic Specification
assume we have a min function for returning the smaller value
The compiler does not know what the T and therefore the compiler behind the scenes will translate into :
func foo() {
let x: Int = ..
let y: Int = ..
let r = min(x, y)
}
will reduce the copy and release and comparing values itself.
Dynamic Dispatch
Apple Swift Blog about Dynamic dispatch
final keyword
Preventing Overrides
You can prevent a method, property, or subscript from being overridden by marking it as final. Do this by writing the
final modifier before the method, property, or subscripts introducer keyword (such as final var, final func, final class
func, and final subscript).
Any attempt to override a final method, property, or subscript in a subclass is reported as a compile-time error.
Methods, properties, or subscripts that you add to a class in an extension can also be marked as final within the
extensions definition.
You can mark an entire class as final by writing the final modifier before the class keyword in its class definition (final
class). Any attempt to subclass a final class is reported as a compile-time error.
Swift compiler have to check every subclass if there are any overriding properties.
After making sure the var name is not available to override , we can add final to inform compiler not need to check the
subclasses of that property
private keyword
mark the method are not allowed to subclass with private so the compiler does not have to check subclass methods that
being overrided
Exposed to Objective-C
dynamic in swift for any property will be obversed by KVO also transfer to Obj-c
Error Handling
is same as
nullability
use the Qualifier for better swift compatibility
helps to clarify the API should accept nil or not
Compiler gives warning if nil is not expected
Use audited Region for wrap all property are not nil
evaluate values is nullable or not first. and then all the elements in the values array must not nil
typed collections
__kindof x * for "some subclass of x
Swift in practices
always use latest SDK to build and set Minimum deployment target for minimum supported OS release
Absence of earlier OS
framework (set the framework as optional)
using #available so that the compiler can help developer to check the system version safely without worrying
class MyClass {
@available(iOS 8.0, *)
func functionThatWithiOS8() {
}
func otherMethod() { ... }
}
let myClass = MyClass()
myClass.otherMethod()
//must use #available to check in order to invoke
if #available(iOS 8.0 , *) {
myClass.functionThatWithiOS8()
}
@available(iOS 8.0, *)
class MyClass {
func functionThatWithiOS8() {
}
func otherMethod() { ... }
}
//must use #available to check in order to invoke
//in iOS 7 the class is not available
if #available(iOS 8.0 , *) {
let myClass = MyClass()
myClass.otherMethod()
myClass.functionThatWithiOS8()
}
Using Enum
A specific enum that solves the issues with strictly typed and no force unwrapping with additional benefits:
1. centrallized constants
2. Does not pollute global namespace
enum UIImage {
enum AssetIndentifer: String {
//in Xcode 7 beta 3, the case name will convert into String if no other value assigned
case Apple
case Orange
case Banana
...
}
//add unwrapped init
convenience init!(assetIdentifer: AssetIndentifer) {
self.init(named: assetIdentifer.rawValue)
}
}
someViewController.swift
override func prepareForSegue(segue: UIStoryBoardSegue, sender: AnyObject?) {
switch segue.identifier {
case "segue1"
case "segue2"
//error as this switch have not default case
}
}
We can use the techique before to wrap the identifer into enum. When we add a new enum case, compiler find the switch
did not handle the case
even so, if we have multiple view controllers, the enum and segue pattern will be repeated. Instead, we can use protocol to
restrict the view controllers to have same enum and functions and we can have all logic in one place.
protocol SegueHandlerType {
//leverage the enum and related swift functions
typealias SegueIdentifier: RawPresentable
}
and use extension to limit what type can use this protocol
if we add a new segue, the compiler will tell us missing handling in prepareForSegue and this promotes compiler time safety.
This also helps reusability of the protocol and helps to reduce the error as constrainting the environment.
Breakpoint enhancement
breakpoints can have names
Other breakpoint commands and use the names
can be set in ~/.lldbinit for default breakpoints
all debug targers inherited with default breakpoints
groupping the breakpoint with -N
Command :
Type Look up
Compiler in LLDB
use p to run swift code ad hoc
p NSApplication.sharedApplication()
In Objc
p NSLog(@"%d", 1)
p NSMakeRect(0,0,10,10)
p [NSApplication sharedApplication].undoManager
will gives proper class signature.(maybe it knows instance type and generic)
LLDB will try internally and assign a variable to the error thrown.
Provides answers
Reveal missed opportunities
and therefore build better app
Preparation
No code
No SDK
App Store and iOS 8+
Users agreed to share App Analytics to developers
Terms - Measures
App Store views - count as one when the user view the app store detailed app page
App unit - the user tapped on "get" or "price tag" button
App Sales - the amount of money of user paid the app including the app prices and in-app purchase if available.
Installations - the amount of installation of the app . if a user installed in iPhone and iPod, that will count as two
Session - the engagement of user to the app
Active device - the recent device that visit the app
Active Lst 30 Days - the device has visied the app at least once for last 30 days
In-App Purchases - the money of users spent on the in-app purchase items
Demensions
App purchase Date
App Version
Campaign
iOS Version
Platform (iPhone, iPad and iPod)
Region
Website
Crashes (New)
Paying Users (New)
Compare Measures
Product Page Conversion Rate (measuring how well of your product page)
App units / App Store Views
Average Revenue Per Paying User
Sales / Paying User
Crashes Per Session ( you don't want this ratio become 1)
Crashes / Sesssions
Session Per Active Device
Source
Identify where the users from and to
Websites
Campaigns
https://itunes.apple.com/us/app/id377298193?mt=8
&pt=1234&ct=My_Campaign
StoreKit
Retention
Supports different builds and versions for internal and external testers
New Metrics for Testers for viewing installs, session and crashes on diff. builds and versions
New limits
grouping app for different managing team with app managers, developers and marketers
App Previews
Testflight enhancement
Transporter
A command line program to uploads and verifies the app meta-data and asset to iTunes Connect. The meta-data includes :
Preparation
Steps
Documents :
Digital Crown
Digital Crown can control pickers natively. Custom controls are also supported via protocol. Coordinated Images are used
for special design like like a clock ring.
Taptic Engine
Different style of haptic can be used.
Media
There is a controller that recording voice on watch
native player controller for playing long-form or stream audio. App is not required to run in background
Alert
Alert API on watch for user confirmation. similar to AlertController
PassKit
Add pass to watch and iPhone wallet
New frameworks
ClockKit
To make complications
Network
Watch can directly access networks if the Phone is not present
Watch Connectivity
New framework for sync the data and files between wath and phone
Core Motion
Core Motion can now used in Watch. Past records can be retrieved for the app and allows querying
Core Location
Watch can get location. Permission are synced with Phone. Once user approved the permission, phone follows.
Health Kit
Similar to Core Motion, Health Kit can be used in Watch as well. Watch can also start workout and retrieve related health
data like heart rates
Security
Watch has its own keychain items. Consideration of data when the device locking or not is in related session.
MapKit
Watch can retrieve directions from MapKit and used that guides user to destination.
Contacts
Likewise, contacts can be seen in watch.
Calendar
Access user's calendar via Event Kit
this is a good blog post of summary for replayKit , GamePlayKit , HomeKit and Search
Apple Developer Program merging into one for any platform and paid once only.
App thinning
App Slicing
32 bit / 64 bit
Images 1x/ 2x/ 3x
GPU shaders (low /high)
App store will deliver needed for the user and thus reducing size of apps.
On demand resources
Sliced for device. Hosted by Apple. Downloaded when needed. Reclaimed the space where needed.
Bitcode
intermediate binary format for submitting to app store. App Store deliver full binary and optimized with latest compiler
available.
therefore , if there are new CPU architecture , develoeprs are not needed to resubmit the app.
watchOS2
Extension runs on Watch instead of on iPhone
NSURLSession
Customized Complication
Time Travel
replace openParentApplication with WatchConnectivity interact with digital crown WKInterfacePicker and WKPickerItem
Style List stack sequence
Foundation
new compression algorithm lvfse battery improvement Security Two-factor authencitation
NSURLSession
exception domains in info.plist IPv6 support
use the networking frameworks
avoid use IPv4-specific APIs
Avoid hard coded addresses
internationalization
App store sales
1. US
2. Japan
3. Chinese
NSPersonNameComponentsFormatter
UIView.userInterfaceLayoutDirectionForSemanticContentAttribute()
Universal Links
application:continueUserActivity:restorationHandler
Search
1. App Search
CoreSpotlight
App Indexing extension
NSUserActivity
Web markup ( from the website mirroring of the app)
multitasking
SlideOver
Split View
-> Adaptive UI
Dynamic Type
Auto layout
Size Classes
Adopt Adaptive UI
Use a launch storyboard
Support all orientations
Picture in Picture
AVPlayerViewController
WKWebview
AVPictureInPictureController
Force Touch
NSPressureConfguration
NSGestureRecoginzer
NSView.pressureChangeWithEvent()
NSEventType.EventTypePressure
CloudKit dashboard
Cloud Web Services
Full access via JSON
JSLibrary
Secure sign in with Apple ID
Swift 2
Open source to Linux with compilers and libraries.
Error Handling
Availability checking
if #available(iOS 9.0, *)
Xcode new feature Header file view (by removing implmentation) Rich comments
Storyboard reference > connections with different storyboard files (no need to put all scenes in a storyboard)
Testing
right click on test cases to see test report UI testing -> record button -> auto generate UI test code
GameKit
New Xcode editor for scenes and 3d Models
Game logics
Replay Kit
Autolayout
iOS 7
dynamic text
iOS 8
Adaptivitiy
Size Classes
View controllers
View controller presentations
Search Result
Action Sheets
iOS 9
Multitasking
Picture in Picture
Related Session:
Getting Started with Multitasking on iPad in iOS 9
Multitasking essentials for media-based apps on iPad in iOS 9
Optimizing Your app for multitasking in iPad iOS 9
UIView
MarginLayoutGuide( available Since iOS 8)
ReadableContentMargin
Make sure the text is readable regardless of users' text size and available spaces
UIStackView
Storyboard
UIViewController
var semanticContentAttribute (override to return value for custom layout)
UIView
var semanticContentAttribute (override to return value for custom layout)
UIImage
func imageFlippedForRightToLeft
var isFlippedForRightToLeft
Related Session :
New UIKit Support for international users interfaces
Accessibility
Change to AVSpeechSynthesis
Related Session :
iOS Accessbility
Text Editing Gesture( text selection gesture on software keyboard with two fingers dragging)
nothing to do to support
make sure custom text view gesture is not conflicting
Touch Events
UIDynamic
Visual Effect
Nullability
Lightweight generics ( subViews are not id instead of UIVew Type)
Related Session :
Whats new in Swift
Notifications
var behavior
var action parameters
Safari
SFSafariViewController
Shared Links
Should appear shared Link
Content Blocking
Related Session :
Audio unit extension
Contacts
Core Location
MapKit
Health Kit
ResearchKit
HomeKit
CloudKit
Related Session :
Whats new in CloudKit
CloudKit tips and tricks
UIDocument
On Demand Resource
App Slicing
Game centre
ReplayKit
GamePlayKit
Related Session :
Introducing GamePlayKit
WatchOS2
Related Session :
Introduction WatchKit for Watch OS 2
1. Playground
2. App Thinning
3. Watch OS Support
4. Instrument Enhancement
5. Crash Log
6. Address sanitizer
7. UI Test
Playground
Playground was first introduced in WWDC 2014. Developer can write pieces of codes (swift only) on it and get response
quickly line by line. It is very useful for prototyping and testing. In this year, Playground has new some improvements:
Playground can be divided in to several pages, developers present and group their codes nicely
Playground's documentation supports Markdown and even creates table of contents and page links. To view
markdown, go to Editor > Show Rendered Markup.
Next Page:
[Next Page](@next)
Previous Page:
[Previous Page](@previous)
Playground can render UIView that you can glance over what you do
App Thinning
It helps developers to deliver their app with smaller app size and let users download the on-demand content when they
need. There are 3 ways to do so:
Bitcode: Xcode will process your binary automatically by this technique. Thus, Apple own a set of processed code
which allow her to generate new app with their updated compiler or architecture in future. And developer can get rid of
app re-submission, Apple do it for you.
App Slicing: Your app is sliced in to pieces by architecture, image sets, etc. Slicing process is automatically done by
Apple after your app submission. All you need to do is put all your assets into image assets. Apple engineers say that
On Demand Resource: By tagging your assets in XCAsset, you can slicing them out of your main bundle. These
bundles are hosted by Apple. You make a bundle request when those on demand resources are going to be shown or
required.
Reference: [link]
Watch OS Support
This year, Apple puts much more effort on Apple Watch. WatchKit is separated out and become Watch OS. Xcode 7
provides an auto-migration tool for migrating from old WatchKit to Watch OS codes.
Instrument Enhancement
add energy efficency profiler
add location request profiler
Crash Log
In Xcode's organizer, a new session is about Crash Log, which is something simular to (clone?) Google Play Exception
Logger or Crashlytics. You can check the crash report from testflight users to app store users. It includes crash device
models, OS versions, crash frequency and even crashed source code position. So, developers can target the crash
issue much accurately.
Address sanitizer
AddressSanitizer (or ASan) is a programming tool that detects memory corruption bugs such as buffer overflows or
accesses to a dangling pointer (use-after-free).
Developers always face with EXC_BAD_ACCESS crash that Xcode point back to main() function. Developers can't trace
back what functions get called before. With ASan, it helps you trace back where the memory corruption is.
UI Test
UI Test is supported in Xcode 7 seamlessly (before you need UIAutomation or Snapshot plugin). Developers simply start a
UI recording session which convert all user interaction as UI testing script. Moreover, developers can insert some testing
script to test the availability of UI elements and its correctness.
ReplayKit
Record Audio and Visual
Ability to Add Voice commentary
HD quality
Privacy safeguard (Record screen & mic / Record Screen / disallow)
Available in iOS 9
For A7 cpu for up
No Direct access of replay video (only via share sheet)
RPScreenRecorderDelegate
if availability changes
if recording stops ( due to error)
RPPreviewController
RPPreviewControllerDelegate
Airplay in use
TV-out in use
Unsupported device(like iPhone 4s iPhone 5)
To solve :
Show UI when the recording is ongoing- like a mic and REC icon use recording propery and microphoneEnabled to
check if the RPScreenRecorder recording has these.
Excluding UI
When to record
Content Blocking
A safari extension for blocking certain kinds of content in the webpage. Use a json file to define what needed to block and
extension loads that json file.
Shared Links
The @ list next to reading list which shows feeds of links under subscribed. In iOS 9 and EL Capitan, native app can add
shared links.
CIFilter Uses one or more CIKernels to create a new image based on inputs
What's new
Metal
As input and output of CIImage
Core Image use Metal to render filters
Some ClFiler use Metal for performance
Filter
40 new filers for iOS Core Image
PDF417 and Code128 generators
Detectors
CIFaceDetector
CIBarcodeDetector
CIRectangleDetector
CITextDetector
Color Management
Supports ICC-based CGColorSpaceRef for input or output
Correct Rendering of TIFFs and JPGs tagged with colorspace
Improved CIKernel
New CIKernel Classes
Improved CIKernel Language
Unified implementation
//in iOS, expose the CALayer and apply CIFiler for best performance
class MyGLKView : GLKView {
}
class MyGLView : UIView {
override class func layerClass() -> AnyClass { return CAEAGLLayer.self }
}
iOS 9
per-app battery usage low power mode environmental factors inteligent suggestions
Xcode
iOS energy gauge
CPU
Networking
Location
Background Location instrument
Networking -
Location -
performed
lower accuracy saves power
set alowDeferredLocationUpdateUntilTraveled:timeout: to give tolerance for system to perform location update while
saving power
Developer benefit
Supported devices
iPhone 6
iPhone 6+
iPad Air 2
iPad mini 3
Merchant ID is required and created in Developer portal (in reserve DNS format)
Developer id and certificate are used to encrypt payment data
User experience
no account setup
no lengthy form
up-to-date billing and shipping address
Request to card & billing , shipping address and contact name but do not request
Shipping options are available
List total and subtotal and discount
Make estimates payment clear
Business name next to total cost as showing charges
Show post-purchase like more information after payment sheet dismissal
Request a payment
PKPaySummaryItem
``` for all checked out products and shipping information
PKPaymentAutherizationViewController
``` the UI display all related information of the payment
PKPaymentAuthorizationViewController.canMakePaymentsUsingNetworks(networks,
capabilities: .CapabilityDebit)
Creating a Payment
creating items
NSDecimalNumber initializers
NSDecimalNumber
NSDecimalNumber(string)
NSDecimalNumber(decimal)
NSDecimalNumber(double)
PKPaymentButton
Acceping a payment
requried delegate
send the payment data to processing servers and return the result in completion block
Contact information
in iOS 8.3
paymentRequest.requiredShippingAddressFields = .Name
Shipping cost
as user select a new address for shipping, this delegate method is invoked. Return the shipping information by call
completion block given.
once the user authorized the payment, shipping contact will be given
AddressBook API is deprecated. all related api convert to use Contact.framework in iOS 9
if paymentMethod.type == .Debit {
// calculating surchages or discounts..
}
pending items (not yet final, refer to latest document) used for the items is not
ready or estimated
paymentSummaryItem.type = .Pending
Apple Watch
QOS
any dispatch_async can assign a Quality of Service values for iOS system to optimize the schedules of threads.
CloudKit Architecture
Public Database
Default zone for CRUD records
Private Database
Default zone for CRUD records
Custom zone for CRUD records
Getting Started
1. create a container
2. create a schema
3. container can be created from either portal or xcode
4. schema can be created from CloudKit web dashboard or on-demend by the app
Swiftification
Subscript
record.setObject(5, forKey:"num")
var aDate = record.objectForKey("date") as! NSDate
change into
record["num"] = 5
var aDate = record["date"]
Light generic
Account Status
Retrying Operations
CKErrorNetworkFailure
Busy Servers
CKErrorServiceUnavailable
and
CKErrorZoneBusy
Rate Limiting
CKErrorRequestRateLimited error is emitted when the quote is hit.
Handling Conflicts
CKErrorServerRecordChanged
``` for the error of conflicting records
retrieve all updated records via ```[CKRecordChangedErrorServerRecordKey``` and append newly created to the end
![](clockKitOneToM.PNG)
## Batch Operation
## Query
**dedicated keys**
**sorting**
Config field sorting via iCloud Dashboard before the records created.
**Pagination**
## Local cache
conflicts
only need to provide the fields need to change and accompanying with CKRecord
Subscriptions
notify app of any changes on
enable APS
entitlement
Registration with UIApplication
Silent Push
setting CKNotificationInfo.shouldSendContentAvailable = true with no alert body, should barge and soundName
retrieve collection of push with CKFetchNotificationChangesOperation and handle background task with
UIApplication.beginBackgroundTaskWithName
Interactive Notificaion
set CKNotificationInfo.category
Performance
use NSOperation dependency to manage tasks relationships for sake of readability and ease for debug
set QoS for NSOperation for let system to handle the operation and perform the tasks
NSUserActivity
NSUserActivity used primary in Handoff which introduced in iOS 8.
1. Create NSUserActivity
2. Added related metadata such as the title, descriptions and thumbnails
3. Add that activity to the index
setting eligibleForHandoff to true that allows that activity can be continues via Hand off
setting eligibleForSearch to true that allows that activity can be as a result in Spotlight
setting expirationDate for the date of expiring any content when the content is not valid in after the expiration date.
Creating NSUserActivity
func application(UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: [AnyObject]? -> Void) -> Bool {
return true
}
Addditional Benefits
CoreSpotlight
treated as database
index for all app content
create, update and delete
adopt by Message, Mail, Calendar and Notes
Steps to create
1. Create CSSearchableItemAttributeSet
2. Create CSSearcableItem
3. Add them to index
attributeSet.title = "Sunrise"
attributeSet.contentDescription = "Nice Sunrise on May 12, 2015"
//Create item with unique id, domainIdentifier for groupping up the the items
let item = CSSearchableItem(uniqueIdentifier: "1", domainIdentifier : "album-1", attributeSet: attributeSet)
CSSearchableIndex.defaultSearchableIndex().indexSearchableItems([Item]) { error in
if error != nil {
//handle error
} else {
//index success
}
}
Restoration
Same API as hand off but the type checked against is CSSearchableItemActionType
func application(UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: [AnyObject]? -> Void) -> Bool {
return true
}
Update
Delete
by domain identifiers
or all
Additional features
extension
Data protection class for more security features
Web markup
As some of the website mirrors the conten of the app. Search in iOS 9 can also shows the results from those websites.
Rich results
Besides showing title and description, images or other media can also used for search results.
Phone number, directions or playing audio or video are actionable for iOS search results.
Resources Link
schema.org http://schema.org
Protecting Relevance
What to index
Setup
//check if the device supports Watch Connectivity (iPhone supports but iPad does not)
if (WCSession.isSupported()) {
let session = WCSession.defaultSession()
session.delegate = self
sesssion.activateSession()
}
//WCSessionDelegate methods
//called whenever the session had changed
func sessionWatchStateDidChange(_ session: WCSession) {
//use this to check if the watch and iPhone are paired
if ( session.paired ) {
...
}
//watchDirectoryURL is not nil if the watch has installed the watch app
if let session.watchDirectoryURL {
}
Communication
Background transfers
Types
Application context
most interesting/ relvent content to deliver
Overriding behavior
In Dictionary
Not in main thread
Recommend to use in Most watch app and glance
//sending
do {
let context = // Create context dictionary with latest state
try WCSession.defaultSession().updateApplicationContext(context)
} catch {
// Handle any errors
}
//receiving
func session(session: WCSession, didReceiveApplicationContext:
applicationContext: [String : AnyObject]) {
// Handle application context dictionary
}
//Sending
let userInfo = // Create dictionary of userInfo
//get transfer object for cancelling
let userInfoTransfer = WCSession.defaultSession().transferUserInfo(userInfo)
//Check outstanding items for transferring
let transfers = WCSession.defaultSession().outstandingUserInfoTransfers()
//Reciving
func session(session: WCSession, didReceiveUserInfo userInfo: [String : AnyObject]) {
// Handle incoming user info dictionary
}
File Transfer
Similar to user info transfer but transferring files
Provided metadata for accompanying the file URL
Must move files to app's space as the inbox of receiver will be clean up once the transfer is finsihed
//Sending
let url = // Retrieve URL of file
let metadata = // Create dictionary of metadata
let fileTransfer = WCSession.defaultSession().transferFile(url,
metadata:metadata)
//Outstanding queue
let transfers = WCSession.defaultSession().outstandingFileTransfers()
// Receiver Callback
func session(session: WCSession, didReceiveFile file: WCSessionFile) {
// Handle file URL and metadata in WCSessionFile object
}
Interactive messaging
Live communication
NSURLSession
requires instant / new content
Content is tailor-made to watch in terms of smaller size or more concise
Usage : Complication
fetch content via NSURLSession while WatchKit Extension in the background
Register via PushKit and set desiredPushTypes as [PKPushTypeComplication]
Upload the push token to the server
receiver push payload via didReceiveIncomingPushWithPayload to transfer timeLineEntry to the watch
session.transferCurrentComplicationUserInfo(presentTimeLineEntry) to transfer
func session(session: WCSession, didReceiveUserInfo userInfo: [String : AnyObject]) to handle the receiver and
update complication
New compressor
lzfse is new compressor in iOS 9 which bring faster compression and higher compression ratio to zlib. Lzfse also is more
energy-efficient than zlib
simd
2D, 3D and 4D vectors and matrices c, Objective-C and c++ and now on swift
Sparse BLAS
New on iOS 9.0 and OSX 10.11 Simple API and good performace Support single and double precision
ATS only active when the app is built with iOS 9 SDK for iOS 9 and OX El Capitan
Use NSAllowsArbitraryLoads for quick triage (allow load all http and https)
NSURLSession on watchOS
NSURLSession availabe in watchOS 2
Best Practices
small screen
limited bandwidth
support TLS
convertion from NSStream
Update
In iOS 9, the developer must add these info.plist
<key>LSApplicationQueriesSchemes</key>
<array>
<string>urlscheme</string>
<string>urlscheme2</string>
<string>urlscheme3</string>
<string>urlscheme4</string>
</array>
to show the intent for calling external apps if the app call canOpenUrl for these urlSchemes
syslog will show capOpenURL: failed for URL: "urlScheme://" - error: null
always return NO
syslog will show capOpenURL: failed for URL: "urlScheme://" - error: null
OS X
Cookies not shared and in sepearated process in El Captian
WatchOS
Privacy setting are shared between paired devices(Watch and Phone) Privacy setting across all extensions
Idenitifers:
Name
Phone number
Randomly generated number
UUID
Best Practices
NSUserActivity
all apps
Extension of iOS 8 handoff app
eligibleForSearch
eligibleForPublicIndexing
expirationDate
OSX 11 will move all third-party binary to user-space from system locations.
Keychain
specialized databases
optimized for searching attributes
efficiently storing for small payload
Consideration
//sample json:
{
"webcredentials":
{
"apps": [
"YWBN8XTPBJ.com.example.app",
"YWBN8XTPBJ.com.example.app-dev"
]
}
}
iCloud Keychain
For all passwords that can be used on multiple devices
Add kSecAttrSynchronizable to all SecItem calls
Warning
Updating or deleting items will affect items on ALL devices
Check SecItem.h
Check iOS security whitepaper
CloudKit Architecture
Private Database will be count towards user's iCloud Storage
public database usage is the same for iOS, OSX and web
authorization
location updates
indoor updates
more accurate
faster detection
region monitoring
iBeacon
Geographic
Visit monitoring
Sig. Location change/ Geocoding/ Reverse-Geocoding
Background location
iOS 4+ background mode
Add UIBackgroundModes
iOS 9 simplifty the workflow
Lower stake
Loose coupling
allowsBackgroundLocationUpdates property per CLLocationManager
Default values: NO
when finish : set it to NO And not tracking the location
MUST UPDATE FOR IOS 9
check with -responsdToSelector:
Audible cue? Related session: What's new in core audio
Single location
requestLocation by giving desiredAccuracy to locationManager .
Automatically (so you dont need to monitor start/stop by yourself, system handled for you)
start (exculsive only one at a time)
threholds internally
calls delegate once locationManager:didUpdateLocations: or locationManager:didFailWithError
stop
// from : http://nshipster.com/ios9/
class ViewController : UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
// ...
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestLocation()
}
// MARK: - CLLocationManagerDelegate
}
}
Authorization
Apple Watch: Best practices
Authorization applies to both Watch and iPhone
requestWhenInUserAuthorization
requestAlwaysAutherization
Background(intermittent) NO YES
Background(continuous) NO NO
Background(intermittent) NO Single
Monitor NO NO
location in use if
blue bar
foreground
handling message from apple watch
requestLocation kCLLocationAccurayHundredMeters
Best effort
Cooperation
if the app need:
continuous background monitoring
Region Monitoring
Anything availabe on iOS but not allowed on watchOS
User WCSession Related session : Introducing Watch Connectivity
sendMessage:replyHandler:errorHanlder: (watch to phone)
Challenges
Best practices
Use performExpiringActivityWithReason(_:, usingBlock:) when being informed the task is being suspended
Historical Accelerometer
collect contiuous data for long durations
Can retrieve even the app is not running
Using the data for custom data analysis
accelerometerDataFrom(_:, to:) -> CMSensorDataList to retrieve the data from a date to a date
Consideration of using
as the data set could be very large, the time of running can be long and again use
performExpiringActivityWithReason(_:, usingBlock:) to monitor if the task is suspended.
consume power
Best practices
Pedometer
Measure
1. step
2. distance
3. floor counting
New in iOS 9
Pace
Cadence
Wikipedia of Cadence)
Cadence in sports involving running is the total number of 'revolutions per minute' (RPM), or number of full cycles taken
within a minute, by the pair of feet, and is used as a measure of athletic performance.
Availability in devices
Pressure
Used to measure relative altitude in floor-scale
we detect the user activity and select the pre-defined playlists. Then according to performace of user activities , the app
changes the songs for cheering the user up. Finally we consolidate the data and shows these to the user.
Use cases
auto-connect wifi hotspots
Personal VPN provider
Enterprise Remote Access
School Filtering
NEHotspotHelper
helps to identify available wifi hotspots and the developers provide confident level for hotspots. Acts as a helper to perform
initial authentication and and maintain the authentication session.
NEVPNManager
NEFilterProvider
on-device filtering
able to update the filtering rules from the internet
customizable block page
app uses webkit that the data will pass though
app is not using webkit, the data will pass though from the socket
Special entitlements for NEHotspotHelper , NETunnelProviderManager and NEFilterProvider and send request at
networkextension@apple.com
iOS Notification
Slient Notification
notify the app
dont need user's approve
background app refresh (beware if user turn off)
Best effort( not 100%!)
User Notification
notify user
requires user permissions
Can be disabled
Local Notification sent by
Time
Location
Remote Notification
Actions (Interactive Notifications)
Categories
Everything supported in WatchOS2
Custom look of notifications
Related Session: WatchKit In-Depth, Path 1 & WatchKit In-Depth, Path 2
Text input
New Actions
Everywhere
Work with Multiple actions
For more in Apple Watch, Related Session: WatchKit In-Depth, Path 1 & WatchKit In-Depth, Path 2
Text input
iOS 8 Competibility
Register different notification actions for different ios version (iOS 8 does not have text input)
Updates in APNS
APNS Feedback Push provider pulls data periodically to validate the tokens
Instant Feedback no need to pulling from Feedback to provider APNS will tell provider if the device token is invalid and the
timestamp of that start invalided.
applications push
VOIP push
Watch Complication push
Development and production environments
NOW ON ONE CERTIFICATE
Push payload from 2KB to 4KB applying all iOS version and OSX
Related Session: Creating Complication with ClockKit, Networking with NSURLSession, Introducting Watch Connectivity