最近项目写 Core Data 感觉之前的看过零碎的知识忘记的差不多了,又遇到异步处理的问题。重新看了一些资料,总结了一些要点如下。

1.

Core Data 是一个 对象图管理和存储框架。简单明确的属性和关系以及获取,都已封装好。不管底层数据库的实现,开发者只需关心数据和获取就行了。

2.

图形化编辑器:xcdatamodel

managed object model :

  • 属性支持 NSData:Binary Data 和符合 NSCoding protocol 的类型:Transformable
  • 关系建议采取 inverse
  • 关系一对多和一对一,其中有有序和无序的一对多的关系,分别为 NSSet 和 NSOrderedSet,具体可以参考这样文章

Core Data and Swift: Relationships and More Fetching :
http://code.tutsplus.com/tutorials/core-data-and-swift-relationships-and-more-fetching--cms-25070

3.

Core Data Stack 涉及四个类:

  • NSManagedObjectModel
  • NSPersistentStore
  • NSPersistentStoreCoordinator
  • NSManagedObjectContext

4.

NSManagedObjectContext:

  • 内存寄存器来处理 managed objects
  • 记得 save()
  • 掌管 managed objects 生命周期包括创建和获取
  • managed object 不能独立于 context 存在
  • context 具有领域性,一旦一个 managed object 被管理在一个 context ,将会在其整个生命周期绑定该 context
  • 支持多个 context
  • context 不是线程安全的

5.

如何配置 Core Data Stack:

其中 lazy、try catch 等技术细节不用多解释,后面在介绍多个 context 和异步处理的线程安全问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
import CoreData

class CoreDataStack {

let modelName = "Dog Walk"

lazy var context: NSManagedObjectContext = {

var managedObjectContext = NSManagedObjectContext(
concurrencyType: .MainQueueConcurrencyType)

managedObjectContext.persistentStoreCoordinator = self.psc
return managedObjectContext
}()

private lazy var psc: NSPersistentStoreCoordinator = {

let coordinator = NSPersistentStoreCoordinator(
managedObjectModel: self.managedObjectModel)

let url = self.applicationDocumentsDirectory
.URLByAppendingPathComponent(self.modelName)

do {
let options =
[NSMigratePersistentStoresAutomaticallyOption : true]

try coordinator.addPersistentStoreWithType(
NSSQLiteStoreType, configuration: nil, URL: url,
options: options)
} catch {
print("Error adding persistent store.")
}

return coordinator
}()

private lazy var managedObjectModel: NSManagedObjectModel = {

let modelURL = NSBundle.mainBundle()
.URLForResource(self.modelName,
withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()

private lazy var applicationDocumentsDirectory: NSURL = {
let urls = NSFileManager.defaultManager().URLsForDirectory(
.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()

func saveContext () {
if context.hasChanges {
do {
try context.save()
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
abort()
}
}
}
}

6.

Fetch

  • NSManagedObjectResultType: 默认值,返回 managed objects
  • NSCountResultType: 返回 count
  • NSDictionaryResultType: 返回一个计算后值,如 sum。详细用法可以看文档 NSExpression
  • NSManagedObjectIDResultType:

从性能优化的角度,可以考虑时候后面的几个类型。
iOS8异步fetch:NSAsynchronousFetchRequest、批量更新/删除属性

7.

fetched results controller 可以帮助我们处理 core data 和 table view datasource,可以简单的看成专用的 datasource。

记得添加 cacheName

8.

后台处理使用 context PrivateQueueConcurrencyType,默认使用 MainQueueConcurrencyType,尤其设计 UI。

可以使用 child context,先保存 child context 至 内存寄存器,一直到 parent context 保存后,才会保存至硬盘。

这里就涉及一个好的实践:有多个 context 总是调用 performBlock 来保证安全。

下面是一个 private context 后台处理,回到主线程的实践:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68


// 1
let privateContext = NSManagedObjectContext(
concurrencyType: .PrivateQueueConcurrencyType)
privateContext.persistentStoreCoordinator =
coreDataStack.context.persistentStoreCoordinator

// 2
privateContext.performBlock { () -> Void in
// 3
let results: [AnyObject]
do {
results = try self.coreDataStack.context
.executeFetchRequest(self.surfJournalFetchRequest())
} catch {
let nserror = error as NSError
print("ERROR: \(nserror)")
results = []
}

let exportFilePath =
NSTemporaryDirectory() + "export.csv"
let exportFileURL = NSURL(fileURLWithPath: exportFilePath)
NSFileManager.defaultManager().createFileAtPath(
exportFilePath, contents: NSData(), attributes: nil)

// 3
let fileHandle: NSFileHandle?
do {
fileHandle = try NSFileHandle(forWritingToURL: exportFileURL)
} catch {
let nserror = error as NSError
print("ERROR: \(nserror)")
fileHandle = nil
}

if let fileHandle = fileHandle {
// 4
for object in results {
let journalEntry = object as! JournalEntry

fileHandle.seekToEndOfFile()
let csvData = journalEntry.csv().dataUsingEncoding(
NSUTF8StringEncoding, allowLossyConversion: false)
fileHandle.writeData(csvData!)
}

// 5
fileHandle.closeFile()

// 4
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.navigationItem.leftBarButtonItem =
self.exportBarButtonItem()
print("Export Path: \(exportFilePath)")
self.showExportFinishedAlertView(exportFilePath)
})
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.navigationItem.leftBarButtonItem =
self.exportBarButtonItem()
})
}

} // 5 Closing brace for performBlock()


9. 参考资料

AVCam-iOSUsingAVFoundationtoCaptureImagesandMovies:
https://github.com/robovm/apple-ios-samples/tree/master/AVCam-iOSUsingAVFoundationtoCaptureImagesandMovies

参考 Apple 的 Objective-C 转化为 Swift 版本。过程中学了不少知识,因没办法 copy-paste,都必须理解相关知识点才行。KVO 、Notification 和多线程等,注释也十分详细。唯一不舒服的就是AVFoundation API 本身没有对 Swift 优化,Swift KVO 也是一个坑。

源码:

https://github.com/gewill/test-projects/tree/master/test%20AVCam

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
//
// JLXCameraViewController.swift
// test AVCam
//
// Created by Will on 4/15/16.
// Copyright © 2016 gewill.org. All rights reserved.
//

import UIKit
import Foundation
import AVFoundation
import Photos
import AssetsLibrary

protocol JLXCameraViewControllerDelegate: NSObjectProtocol {
func cameraViewController(vc: JLXCameraViewController, didFinishCaptureVideoUrl url: NSURL!)
func cameraViewControllerDidCancel(vc: JLXCameraViewController)
}

enum JLXAVCamSetupResult {
case Success
case CameraNotAuthorized
case SessionConfiguratonFailed
}

private var SessionRunningContext = 0

class JLXCameraViewController: UIViewController, AVCaptureFileOutputRecordingDelegate {
@IBOutlet var previewView: JLXPreviewView!

@IBOutlet var cameraUnavailableLabel: UILabel!
@IBOutlet var resumeButton: UIButton!

@IBOutlet var flashButton: UIButton!
@IBOutlet var changeCameraButton: UIButton!
@IBOutlet var cancelButton: UIButton!

@IBOutlet var durationLabel: UILabel!

@IBOutlet var recordButton: UIButton!

var delegate: JLXCameraViewControllerDelegate?

// Session management

// Communicate with the session and other session objects on this queue.
var sessionQueue = dispatch_queue_create("session queue", DISPATCH_QUEUE_SERIAL)
dynamic var session: AVCaptureSession!
var videoDeviceInput: AVCaptureDeviceInput!
var movieFileOutput: AVCaptureMovieFileOutput!

// Utilities
var setupResult: JLXAVCamSetupResult!
var sessionRunning: Bool!
var backgroundRecordingId: UIBackgroundTaskIdentifier!
var durationTimer: NSTimer?
var seconds: Int!
var isRecording = false

// MARK: - life cycle

override func viewDidLoad() {
super.viewDidLoad()

self.setupUI()

self.setupSession()
}

func setupUI() {
// Disable UI. The UI is enabled if and only if the session starts running.
self.changeCameraButton.enabled = false
self.recordButton.enabled = false
self.flashButton.enabled = false

self.resumeButton.setTitle("Tap to resume", forState: .Normal)
self.resumeButton.hidden = true
self.cameraUnavailableLabel.text = "Camera Unavailable"
self.cameraUnavailableLabel.hidden = true

let tapGesture = UITapGestureRecognizer(target: self, action: #selector(JLXCameraViewController.focusAndExposeTap(_:)))
self.previewView.addGestureRecognizer(tapGesture)
}

func setupAuthorization() {
// Check video authorization status. Video access is required and audio access is optional.
// If audio access is denied, audio is not recorded during movie recording.

switch AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo) {
case AVAuthorizationStatus.NotDetermined:
dispatch_suspend(self.sessionQueue)
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo, completionHandler: { (granted) in
if granted == false {
self.setupResult = JLXAVCamSetupResult.CameraNotAuthorized
}
dispatch_resume(self.sessionQueue)
})
case AVAuthorizationStatus.Authorized:
self.setupResult = JLXAVCamSetupResult.Success
default:
self.setupResult = JLXAVCamSetupResult.CameraNotAuthorized
}
}

// Setup the capture session.
// In general it is not safe to mutate an AVCaptureSession or any of its inputs, outputs, or connections from multiple threads at the same time.
// Why not do all of this on the main queue?
// Because -[AVCaptureSession startRunning] is a blocking call which can take a long time. We dispatch session setup to the sessionQueue
// so that the main queue isn't blocked, which keeps the UI responsive.
func setupSession() {
// Create the AVCaptureSession.
self.session = AVCaptureSession()

// Setup the preview view.
self.previewView.setSession(self.session)

self.setupResult = JLXAVCamSetupResult.Success

self.setupAuthorization()

dispatch_async(self.sessionQueue) {
if self.setupResult != JLXAVCamSetupResult.Success {
return
}

self.backgroundRecordingId = UIBackgroundTaskInvalid

let videoDevice: AVCaptureDevice = JLXCameraViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: AVCaptureDevicePosition.Back)

var videoDeviceInput: AVCaptureDeviceInput?
do {
videoDeviceInput = try AVCaptureDeviceInput.init(device: videoDevice)
} catch let error as NSError {
print("Could not create video device input: \(error.debugDescription)")
}

self.session.beginConfiguration()

if self.session.canAddInput(videoDeviceInput) {
self.session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput

dispatch_async(dispatch_get_main_queue()) {
// Why are we dispatching this to the main queue?
// Because AVCaptureVideoPreviewLayer is the backing layer for AAPLPreviewView and UIView
// can only be manipulated on the main thread.
// Note: As an exception to the above rule, it is not necessary to serialize video orientation changes
// on the AVCaptureVideoPreviewLayer’s connection with other session manipulation.

// Use the status bar orientation as the initial video orientation. Subsequent orientation changes are handled by
// -[viewWillTransitionToSize:withTransitionCoordinator:].
let orientation = AVCaptureVideoOrientation.LandscapeRight
let previewLayer = self.previewView.layer as! AVCaptureVideoPreviewLayer
previewLayer.connection.videoOrientation = orientation
}
} else {
print("Could not add video device input to the session")
self.setupResult = JLXAVCamSetupResult.SessionConfiguratonFailed
}

// TODO: - test failed
let audioDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeAudio)
let audioDeviceInput: AVCaptureDeviceInput?
do {
audioDeviceInput = try AVCaptureDeviceInput.init(device: audioDevice)
} catch let error as NSError {
print("Could not create audio device input: \(error.debugDescription.debugDescription)")
}

let movieFileOutput = AVCaptureMovieFileOutput()
if self.session.canAddOutput(movieFileOutput) {
self.session.addOutput(movieFileOutput)
let connection = movieFileOutput.connectionWithMediaType(AVMediaTypeVideo)
if #available(iOS 8.0, *) {
if connection.supportsVideoStabilization {
connection.preferredVideoStabilizationMode = .Auto
}
} else {
connection.enablesVideoStabilizationWhenAvailable = true
}

if connection.supportsVideoOrientation {
connection.videoOrientation = AVCaptureVideoOrientation.LandscapeRight
}

self.movieFileOutput = movieFileOutput
} else {
print("Could not add movie file output to the session")
self.setupResult = JLXAVCamSetupResult.SessionConfiguratonFailed
}

self.session.commitConfiguration()
}
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)

// response setupResult

dispatch_async(self.sessionQueue) {
if let result = self.setupResult {
switch result {
case .Success:
// Only setup observers and start the session running if setup succeeded.
self.addObservers()
self.session.startRunning()
self.sessionRunning = self.session.running
case .CameraNotAuthorized:
dispatch_async(dispatch_get_main_queue()) {
let title = NSBundle.mainBundle().localizedInfoDictionary!["CFBundleName"] as! String
let message = String.localizedStringWithFormat("AVCam doesn't have permission to use the camera, please change privacy settings", "Alert message when the user has denied access to the camera")
let cancelText = String.localizedStringWithFormat("OK", "Alert OK button")
let settingsText = String.localizedStringWithFormat("Settings", "Alert button to open Settings")
if #available(iOS 8.0, *) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: cancelText, style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(cancelAction)
let settingsAction = UIAlertAction(title: settingsText, style: UIAlertActionStyle.Default, handler: { (action) in
UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!)
})
alertController.addAction(settingsAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
let alert = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: cancelText, otherButtonTitles: settingsText)
alert.show()
}
}
case .SessionConfiguratonFailed:
let title = NSBundle.mainBundle().localizedInfoDictionary!["CFBundleName"] as! String
let message = String.localizedStringWithFormat("Unable to capture media", "Alert message when something goes wrong during capture session configuration")
let cancelText = String.localizedStringWithFormat("OK", "Alert OK button")
if #available(iOS 8.0, *) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: cancelText, style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
let alert = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: cancelText)
alert.show()
}
}
}
}
}

override func viewDidDisappear(animated: Bool) {
dispatch_async(self.sessionQueue) {
if self.setupResult == JLXAVCamSetupResult.Success {
self.session.stopRunning()
self.removeObservers()
}
}

super.viewDidDisappear(animated)
}

// MARK: - Orientation

override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.LandscapeRight
}

// MARK: - KVO and Notifications

func addObservers() {
self.session.addObserver(self, forKeyPath: "running", options: NSKeyValueObservingOptions.New, context: &SessionRunningContext)

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(subjectAreaDidChange(_:)), name: AVCaptureDeviceSubjectAreaDidChangeNotification, object: self.videoDeviceInput.device)
// A session can only run when the app is full screen. It will be interrupted
// in a multi-app layout, introduced in iOS 9,
// see also the documentation of AVCaptureSessionInterruptionReason. Add
// observers to handle these session interruptions
// and show a preview is paused message. See the documentation of
// AVCaptureSessionWasInterruptedNotification for other
// interruption reasons.
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(sessionWatInterruptedEnded(_:)), name: AVCaptureSessionWasInterruptedNotification, object: self.session)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(sessionWatInterruptedEnded(_:)), name: AVCaptureSessionInterruptionEndedNotification, object: self.session)
}

func removeObservers() {
self.session.removeObserver(self, forKeyPath: "running", context: &SessionRunningContext)

NSNotificationCenter.defaultCenter().removeObserver(self)
}

override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String: AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &SessionRunningContext {
if let isSessionRunning = change?[NSKeyValueChangeNewKey]?.boolValue where
isSessionRunning == true {
dispatch_async(dispatch_get_main_queue()) {
// Only enable the ability to change camera if the device has more than
// one camera.
self.changeCameraButton.enabled = isSessionRunning && (AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo).count > 1)
self.recordButton.enabled = isSessionRunning
}
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}

func subjectAreaDidChange(notification: NSNotification) {
let devicePoiont = CGPoint(x: 0.5, y: 0.5)
self.focusWithMode(AVCaptureFocusMode.ContinuousAutoFocus, exposureWithMode: AVCaptureExposureMode.ContinuousAutoExposure, atDevicePoint: devicePoiont, monitorSubjectAreaChange: false)
}

func sessionRuntimeError(notification: NSNotification) {
// Automatically try to restart the session running if media services were
// reset and the last start running succeeded.
// Otherwise, enable the user to try to resume the session running.
if let error = notification.userInfo?[AVCaptureSessionErrorKey] where
error.code == AVError.MediaServicesWereReset.rawValue {
dispatch_async(self.sessionQueue, {
if self.sessionRunning == true {
self.session.startRunning()
self.sessionRunning = self.session.running
} else {
dispatch_async(dispatch_get_main_queue(), {
self.resumeButton.hidden = false
})
}
})
} else {
self.resumeButton.hidden = false
}
}

func sessionWasInterrupted(notification: NSNotification) {
// In some scenarios we want to enable the user to resume the session running.
// For example, if music playback is initiated via control center while using AVCam,
// then the user can let AVCam resume the session running, which will stop music playback.
// Note that stopping music playback in control center will not automatically resume the session running.
// Also note that it is not always possible to resume, see -[resumeInterruptedSession:].

var showResumeButton = false

// In iOS 9 and later, the userInfo dictionary contains information on why the
// session was interrupted.
if #available(iOS 9.0, *) {
if let reason = notification.userInfo?[AVCaptureSessionInterruptionReasonKey] where reason is Int
{
if (reason as! Int) == AVCaptureSessionInterruptionReason.AudioDeviceInUseByAnotherClient.rawValue || (reason as! Int) == AVCaptureSessionInterruptionReason.VideoDeviceInUseByAnotherClient.rawValue {
showResumeButton = true
} else if (reason as! Int) == AVCaptureSessionInterruptionReason.VideoDeviceNotAvailableWithMultipleForegroundApps.rawValue {
// Simply fade-in a label to inform the user that the camera is
// unavailable.
self.cameraUnavailableLabel.hidden = false
self.cameraUnavailableLabel.alpha = 0
UIView.animateWithDuration(0.25, animations: {
self.cameraUnavailableLabel.alpha = 1
})
}
}
} else {
print("Capture session was interrupted")
showResumeButton = UIApplication.sharedApplication().applicationState == UIApplicationState.Inactive
}

if showResumeButton {
// Simply fade-in a button to enable the user to try to resume the session
// running.
self.resumeButton.hidden = false
self.resumeButton.alpha = 0
UIView.animateWithDuration(0.25, animations: {
self.resumeButton.alpha = 1
})
}
}

func sessionWatInterruptedEnded(notification: NSNotification) {
print("Capture session interruption ended")

// hide buttons with animations
if !self.resumeButton.hidden {
UIView.animateWithDuration(0.25, animations: {
self.resumeButton.alpha = 0
}, completion: { (finished) in
self.resumeButton.hidden = true
})
}

if !self.cameraUnavailableLabel.hidden {
UIView.animateWithDuration(0.25, animations: {
self.cameraUnavailableLabel.alpha = 0
}, completion: { (finished) in
self.cameraUnavailableLabel.hidden = true
})
}
}

// MARK: - Response Actions

@IBAction func resumeButtonClick(sender: AnyObject) {
dispatch_async(self.sessionQueue) {
// The session might fail to start running, e.g., if a phone or FaceTime
// call is still using audio or video.
// A failure to start the session running will be communicated via a session
// runtime error notification.
// To avoid repeatedly failing to start the session running, we only try to
// restart the session running in the
// session runtime error handler if we aren't trying to resume the session
// running.
self.session.startRunning()
self.durationTimer = NSTimer(timeInterval: 1.0, target: self, selector: #selector(JLXCameraViewController.refreshDurationLabel), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(self.durationTimer!, forMode: NSRunLoopCommonModes)
self.durationTimer?.fire()

self.sessionRunning = self.session.running
if !self.session.running {
dispatch_async(dispatch_get_main_queue()) {
let title = NSBundle.mainBundle().localizedInfoDictionary!["CFBundleName"] as! String
let message = String.localizedStringWithFormat("Unable to resume", "Alert message when unable to resume the session running")
let cancelText = String.localizedStringWithFormat("OK", "Alert OK button")
if #available(iOS 8.0, *) {
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: cancelText, style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
} else {
let alert = UIAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: cancelText)
alert.show()
}
}
} else {
dispatch_async(dispatch_get_main_queue()) {
self.resumeButton.hidden = false
}
}
}
}
@IBAction func recordButtonClick(sender: AnyObject) {
// Disable the Camera button until recording finishes, and disable the Record
// button until recording starts or finishes. See the
// AVCaptureFileOutputRecordingDelegate methods.
self.changeCameraButton.enabled = false
self.recordButton.enabled = false

if self.isRecording == true {
self.durationTimer?.invalidate()
self.durationTimer = nil
self.seconds = 0
self.durationLabel.text = secondsToFormatTimeFull(0)
} else {
self.seconds = 0
self.durationTimer = NSTimer(timeInterval: 1.0, target: self, selector: #selector(JLXCameraViewController.refreshDurationLabel), userInfo: nil, repeats: true)
NSRunLoop.currentRunLoop().addTimer(self.durationTimer!, forMode: NSRunLoopCommonModes)
self.durationTimer?.fire()
}

self.isRecording = !isRecording

dispatch_async(self.sessionQueue) {
if !self.movieFileOutput.recording && UIDevice.currentDevice().multitaskingSupported {
// Setup background task. This is needed because the
// -[captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:]
// callback is not received until AVCam returns to the foreground unless
// you request background execution time.
// This also ensures that there will be time to write the file to the
// photo library when AVCam is backgrounded.
// To conclude this background execution, -endBackgroundTask is called
// in
// -[captureOutput:didFinishRecordingToOutputFileAtURL:fromConnections:error:]
// after the recorded file has been saved.
self.backgroundRecordingId = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler(nil)

// Turn OFF flash for video recording.
JLXCameraViewController.setFlashMode(AVCaptureFlashMode.Off, forDevice: self.videoDeviceInput.device)

// Start recording to a temporary file.
let outputFileName = NSProcessInfo.processInfo().globallyUniqueString
let outputFileUrl = NSURL(fileURLWithPath: NSTemporaryDirectory()).URLByAppendingPathComponent(outputFileName).URLByAppendingPathExtension("mov")
self.movieFileOutput.startRecordingToOutputFileURL(outputFileUrl, recordingDelegate: self)
} else {
self.movieFileOutput.stopRecording()
}
}
}

@IBAction func changeCameraButtonClick(sender: AnyObject) {
self.changeCameraButton.enabled = false
self.recordButton.enabled = false

dispatch_async(self.sessionQueue) {
let currentVideoDivice = self.videoDeviceInput.device
var preferredPosition = AVCaptureDevicePosition.Unspecified
let currentPosition = currentVideoDivice.position

switch currentPosition {
case AVCaptureDevicePosition.Front:
preferredPosition = AVCaptureDevicePosition.Back
case AVCaptureDevicePosition.Back:
preferredPosition = AVCaptureDevicePosition.Front
default:
break
}

let videoDevice = JLXCameraViewController.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: preferredPosition)

var videoDeviceInput: AVCaptureDeviceInput?
do {
videoDeviceInput = try AVCaptureDeviceInput.init(device: videoDevice)
} catch let error as NSError {
print("Could not create video device input: \(error.debugDescription)")
}

self.session.beginConfiguration()

// Remove the existing device input first, since using the front and back
// camera simultaneously is not supported.
self.session.removeInput(self.videoDeviceInput)

if self.session.canAddInput(videoDeviceInput) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: AVCaptureDeviceSubjectAreaDidChangeNotification, object: currentVideoDivice)

JLXCameraViewController.setFlashMode(AVCaptureFlashMode.Auto, forDevice: videoDevice)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(JLXCameraViewController.subjectAreaDidChange(_:)), name: AVCaptureDeviceSubjectAreaDidChangeNotification, object: videoDevice)

self.session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput
} else {
self.session.addInput(self.videoDeviceInput)
}

let connection = self.movieFileOutput.connectionWithMediaType(AVMediaTypeVideo)
if connection.supportsVideoStabilization {
if #available(iOS 8.0, *) {
connection.preferredVideoStabilizationMode = .Auto
} else {
connection.enablesVideoStabilizationWhenAvailable = true
}
}

self.session.commitConfiguration()

dispatch_async(dispatch_get_main_queue()) {
self.changeCameraButton.enabled = true
self.recordButton.enabled = true
}
}
}

func focusAndExposeTap(gestureRecognizer: UIGestureRecognizer) {
let devicePoint = (self.previewView.layer as! AVCaptureVideoPreviewLayer).captureDevicePointOfInterestForPoint(gestureRecognizer.locationInView(gestureRecognizer.view))
self.focusWithMode(AVCaptureFocusMode.AutoFocus, exposureWithMode: AVCaptureExposureMode.AutoExpose, atDevicePoint: devicePoint, monitorSubjectAreaChange: true)
}

@IBAction func flashButtonClick(sender: AnyObject) {
// TODO: - should deal while changeCameraButton
}

func refreshDurationLabel() {
seconds = seconds + 1
self.durationLabel.text = secondsToFormatTimeFull(Double(self.seconds))
}

@IBAction func cancelButtonClick(sender: AnyObject) {
delegate?.cameraViewControllerDidCancel(self)
self.dismissViewControllerAnimated(true, completion: nil)
}

// MARK: - File Output Recording Delegate
func captureOutput(captureOutput: AVCaptureFileOutput!, didStartRecordingToOutputFileAtURL fileURL: NSURL!, fromConnections connections: [AnyObject]!) {
// Enable the Record button to let the user stop the recording.
dispatch_async(dispatch_get_main_queue()) {
self.recordButton.enabled = true
self.recordButton.setTitle(String.localizedStringWithFormat("Stop", "Recording button stop title"), forState: .Normal)
}
}

func captureOutput(captureOutput: AVCaptureFileOutput!, didFinishRecordingToOutputFileAtURL outputFileURL: NSURL!, fromConnections connections: [AnyObject]!, error: NSError!) {
// Note that currentBackgroundRecordingID is used to end the background task
// associated with this recording.
// This allows a new recording to be started, associated with a new
// UIBackgroundTaskIdentifier, once the movie file output's isRecording
// property
// is back to NO — which happens sometime after this method returns.
// Note: Since we use a unique file path for each recording, a new recording
// will not overwrite a recording currently being saved.

self.delegate?.cameraViewController(self, didFinishCaptureVideoUrl: outputFileURL)
self.dismissViewControllerAnimated(true, completion: nil)
}

// MARK: - Device Configuration
func focusWithMode(focusMode: AVCaptureFocusMode, exposureWithMode exposureMode: AVCaptureExposureMode, atDevicePoint point: CGPoint, monitorSubjectAreaChange: Bool) {
dispatch_async(self.sessionQueue) {
let device = self.videoDeviceInput.device
do {
try device.lockForConfiguration()
// Setting (focus/exposure)PointOfInterest alone does not initiate a
// (focus/exposure) operation.
// Call -set(Focus/Exposure)Mode: to apply the new point of interest.
if device.focusPointOfInterestSupported && device.isFocusModeSupported(AVCaptureFocusMode.AutoFocus) {
device.focusPointOfInterest = point
device.focusMode = focusMode
}

if device.exposurePointOfInterestSupported && device.isExposureModeSupported(AVCaptureExposureMode.AutoExpose) {
device.exposurePointOfInterest = point
device.exposureMode = exposureMode
}

device.subjectAreaChangeMonitoringEnabled = monitorSubjectAreaChange

device.unlockForConfiguration()
} catch let error as NSError {
print(" \(error.debugDescription)")
}
}
}

class func setFlashMode(flashMode: AVCaptureFlashMode, forDevice device: AVCaptureDevice) {
if device.hasFlash && device.isFlashModeSupported(flashMode) {
do {
try device.lockForConfiguration()
device.flashMode = flashMode
device.unlockForConfiguration()
} catch let error as NSError {
print("Could not lock device for configuration: \(error.debugDescription)")
}
}
}

class func deviceWithMediaType(mediaType: String, preferringPosition position: AVCaptureDevicePosition) -> AVCaptureDevice {
let devices = AVCaptureDevice.devicesWithMediaType(mediaType) as![AVCaptureDevice!]
var captureDevice = devices.first

for device in devices {
if device.position == position {
captureDevice = device
break
}
}

return captureDevice!
}
}

WWDC 2011 - Session 405 - Exploring AV Foundation
https://developer.apple.com/videos/play/wwdc2011/405/

1. 扯淡

可以学习英文教程,但要循序渐进,之后总结实践很重要。转化为自己的理解才行。之前看了一段时间 Doctmentation,感觉很大很复杂的框架。之后动手写了一些代码,回头再看相关 Session 就豁然开朗,一切不过是熟悉 Cocoa 框架结构,无非就是本事视频相关的不熟悉,直接开发就比较抽象。开发实践中持续学习,也就进入佳境。

视频学习时,双屏必备利器。加上最近 iPad 在 Session Keynote 上笔记,效率很高。

Session 不停的示例代码非常易于理解。

2. 总结

Keynote 要点如下:

  1. 五大功能:检测/播放/编辑片段/导出/录制。
  2. 两种媒体 model:static/dynamic, 类似NSArray/NSMutableArray,对应读取时是否会 mutate。
  3. 异步加载
  4. Key-Value Observe 支持大多数属性
  5. “There’s a protocol for that” TM
  6. AVPlayerItem: AVAsynchronousKeyValueLoading:loadValuesAsynchronouslyForKeys(_:completionHandler:),可以异步获取状态/属性变化,以更新 UI 等。
  7. AVPlayer 时间属性变化很快,异步 KVO 不再合适,改为同步 KVO,需要添加/移除观察:addPeriodicTimeObserverForInterval(_:queue:usingBlock:)
  8. AVPlayerItem 可获取媒体相关的属性,对 status 添加KVO。
  9. AVPlayerItemTrack:enabled 属性可以选择性播放 track。
  10. AVQueuePlayer:播放一组 AVAsset,适用于编辑完播放。
  11. AVPlayerLayer 用于显示媒体在屏幕上。有 readyForDisplay/videoGravity 等属性。
  12. AVMediaSelectionGroup 用于字幕/音频等可选 track。
  13. iPod Library: MPMediaQuery
  14. Camera Roll: AssetsLibrary (iOS 9: Photos)
  15. static/dynamic model 对应不同的观察机制,如下:

Matters of protocol And platform etiquette

  • AVAsynchronousKeyValueLoading
1
2
loadValuesAsynchronouslyForKeys:completionHandler: 
statusOfValueForKey:error:
  • NSObject(NSKeyValueObserving)
1
2
3
addObserver:forKeyPath:options:context: 
removeObserver:forKeyPath:
observeValueForKeyPath:ofObject:change:context:

3. 部分示例代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
NSArray *keys = [NSArray arrayWithObject:@”playable”];
[asset
loadValuesAsynchronouslyForKeys:keys
completionHandler:^{
NSError *error = nil;
AVKeyValueStatus playableStatus =
[asset statusOfValueForKey:@"playable" error:&error];
switch (playableStatus) {
case AVKeyValueStatusLoaded:
[self updateUIForAsset];
break;
case AVKeyValueStatusFailed:
[self reportError:error forAsset:asset];
break;
...
}
}];
1
2
3
4
5
6
7
8
9
10
11
12
13
14
- (void)setUpTransportUI {
CMTime interval = CMTimeMakeWithSeconds(0.5);
id myObserver =
[[myPlayer addPeriodicTimeObserverForInterval:interval
queue:dispatch_get_main_queue()
usingBlock:^{
[self movePlayheadUI];
}] retain];
}

- (void)cleanUp {
[myPlayer removeTimeObserver:myObserver];
[myObserver release];
}

最近项目需要自定义一个 UIView,虽然不是第一次做,但是还是出现了很多问题,其中最严重是的获取的 self.bounds 是不对。

Debug 能力真的需要提高了,调试了很久,还是靠断点,逐个对比 bounds 才知道问题所在。

http://stackoverflow.com/questions/29763818/making-a-custom-uiview-subview-that-fills-its-superview

这一篇解释的很清楚,我自己混淆了几种方法的使用,还忘记了手动设置 frame 时,还忘了layoutSubviews()。以前可能是宽高确定或根据 UIScreen 来的计算的,一直没出现问题。

  1. Use Auto Layout
    • Interface Builder
    • Programmatically
  2. Manual Layout
    • Resizing Masks
    • Layout Subviews

关键代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}

required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupViews()
}

private func setupViews() {

let view = UIView(frame: CGRectZero)
view.setTranslatesAutoresizingMaskIntoConstraints(false)
super.init(frame: frame)
let viewsDict = ["view": view]
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[view]-0-|", options: .allZeros, metrics: nil, views: viewsDict))
addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[view]-0-|", options: .allZeros, metrics: nil, views: viewsDict))
addSubview(view)

}

原因

viewDidLoad 时获取的size 可能是错误的。

viewDidLoad

The view controller has obtained its view. See the discussion earlier in this chapter of how a view controller gets its view. Recall that this does not mean that the view is in the interface or even that it has been given its correct size.

Core Animation Essentials (WWDC 2011 - Session 421):

https://developer.apple.com/videos/play/wwdc2011/421/

Animations Explained:

https://www.objc.io/issues/12-animations/animations-explained/#a-basic-animation

According above two documents,write code again by myself.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import UIKit
import QuartzCore

class ViewController: UIViewController {
let layer = CALayer()

override func viewDidLoad() {
super.viewDidLoad()

self.addImageLayer()
}

func addImageLayer() {

layer.bounds = CGRect(x: 0, y: 0, width: 25, height: 25)
layer.position = CGPoint(x: 100, y: 100)
let image = UIImage(named: "yanFei")!
layer.contents = image.CGImage

self.view.layer.addSublayer(layer)
}

@IBAction func stopButtonClick(sender: AnyObject) {
}
@IBAction func firstButtonClick(sender: AnyObject) {
layer.opacity = 0
}
@IBAction func secendButtonClick(sender: AnyObject) {
// Just disable current run loop transaction
// CATransaction.setDisableActions(true)

CATransaction.setAnimationDuration(2)
layer.opacity = 1
layer.position = CGPoint(x: 100, y: 400)
}
@IBAction func thirdButtonClick(sender: AnyObject) {
CATransaction.setAnimationDuration(5)
layer.position = CGPoint(x: 0, y: UIScreen.mainScreen().bounds.height)
layer.opacity = 0
}

@IBAction func fourthButtonClick(sender: AnyObject) {

layer.position = CGPoint(x: layer.position.x, y: 400)

let drop = CABasicAnimation(keyPath: "position.y")
drop.fromValue = 30
drop.toValue = 400
drop.duration = 5
drop.delegate = self
// drop.beginTime = CACurrentMediaTime() + 0.5
layer.addAnimation(drop, forKey: nil)
}
@IBAction func fivethButtonClick(sender: AnyObject) {

let shake = CAKeyframeAnimation(keyPath: "position.x")
// values or path
shake.values = [0, 10, -10, 10, 0]
shake.keyTimes = [0, 1 / 6.0, 3 / 6.0, 5 / 6.0, 1]
shake.duration = 0.4

shake.additive = true

shake.delegate = self

layer.addAnimation(shake, forKey: "shake")
}

@IBAction func sixthButtonClick(sender: AnyObject) {

let boundingRect = CGRect(x: -50, y: -50, width: 100, height: 100)

let orbit = CAKeyframeAnimation(keyPath: "position")
orbit.path = CGPathCreateWithEllipseInRect(boundingRect, nil)
orbit.duration = 4
orbit.additive = true
orbit.repeatCount = Float.infinity
orbit.calculationMode = kCAAnimationPaced
orbit.rotationMode = kCAAnimationRotateAuto

layer.addAnimation(orbit, forKey: "orbit")
}

@IBAction func seventhButtonClick(sender: AnyObject) {

layer.position = CGPoint(x: 300, y: layer.position.y)

let timing = CABasicAnimation(keyPath: "position.x")
timing.fromValue = 30
timing.toValue = 300
timing.duration = 2

// timing.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
timing.timingFunction = CAMediaTimingFunction(controlPoints: 0.5, 0, 0.9, 0.7)
layer.addAnimation(timing, forKey: "timing")
}

@IBAction func eighthButtonClick(sender: AnyObject) {

let zPosistion = CABasicAnimation(keyPath: "zPosition")
zPosistion.fromValue = -1
zPosistion.toValue = 1
zPosistion.duration = 1.2

let rotation = CAKeyframeAnimation(keyPath: "transform.rotation")
rotation.values = [0, 0.14, 0]
rotation.duration = 1.2
rotation.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)]

let position = CAKeyframeAnimation(keyPath: "position")
position.values = [NSValue(CGPoint: CGPointZero), NSValue(CGPoint: CGPoint(x: 110, y: -20)), NSValue(CGPoint: CGPointZero)]
position.timingFunctions = [CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut),
CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut)]
position.duration = 1.2
position.additive = true

let group = CAAnimationGroup()
group.animations = [zPosistion, rotation, position]
group.duration = 1.2
group.beginTime = CACurrentMediaTime() + 0.5

layer.addAnimation(group, forKey: nil)

layer.zPosition = 1
}
}

extension ViewController {
override func animationDidStart(anim: CAAnimation) {
print(anim)
}

override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
print(anim)
}
}

Demo link:
https://github.com/gewill/test-projects/tree/master/test%20Core%20Animation

When we design function or API, have to choose parameters default values. Here are 3 common styles.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
enum UserType: String {
case Weixin = "wechat"
case Weibo = "weibo"
case QQ = "qq"
}

// 1. Like NSLayoutAnchor, call function can be like less input parameters
func testDefaultParametersValue(userType: UserType = .Weibo) {
print(userType)
}


testDefaultParametersValue()
testDefaultParametersValue(.QQ)

// 2. All parameters have to input
func testOptionalParametersValue(var userType: UserType?) {
// Can set default value inside too
if userType == nil {
userType = .Weibo
}

print(userType)
}

testOptionalParametersValue(nil)
testOptionalParametersValue(.Weixin)


// 3. Like Kingfisher can less parameters or pass nil
func testAll(id: Int? = nil, city: String) {
print(id)
print(city)
}

testAll(city: "Shanghai")
testAll(nil, city: "Shanghai")
testAll(12, city: "Shanghai")

Use resursion to get more 90% data, still can’t upto 100%.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96

import Foundation
import Alamofire
import SwiftyJSON
import Alamofire-SwiftyJSON
import RealmSwift

// MARK: - friendships

// Weibo 30% more or less limits how to aovid this.
// Thus count each response json user nubmer, to calculate true next cursor.
// But Weibo return much fewer than 30%, fanially we got 93% data.
// http://open.weibo.com/wiki/2/friendships/friends

static func allFriends(uid uid: Int?, cursor: Int?, completionHandler: (stateCode: WeiboServiceError, error: String?, nextCursor: Int?) -> Void) {

let pageNumber: Int = 200
var parameters: [String: AnyObject] = ["count": pageNumber]

AccountManager.currentAcvtiveWeiboAccount { (stateCode, error, weiboAccount) -> Void in
if let weiboAccount = weiboAccount {
parameters.updateValue(weiboAccount.accessToken, forKey: "access_token")
parameters.updateValue(weiboAccount.accountId, forKey: "uid")
}
}

if let uid = uid {
parameters.updateValue(uid, forKey: "uid")
}
if let cursor = cursor {
parameters.updateValue(cursor, forKey: "cursor")
}
Alamofire.request(.GET, WeiboApi.FriendshipsFriends, parameters: parameters)
.responseSwiftyJSON({ (request, response, json, error) in
if error != nil {
completionHandler(stateCode: .Error, error: "Please check internet connection.", nextCursor: nil)
} else if json["error"] != JSON.null {
completionHandler(stateCode: .Error, error: json["error"].stringValue, nextCursor: nil)
} else {
WeiboStore.friendsJSONToUserAndSave(json: json, completionHandler: { (stateCode, error, count) -> Void in
if stateCode == .Error {
completionHandler(stateCode: .Error, error: error, nextCursor: nil)
} else {

let previousCursor = json["previous_cursor"].intValue
let nextCursor = previousCursor + count!

if count > 0 {

self.allFriends(uid: uid, cursor: nextCursor, completionHandler: { (stateCode, error, nextCursor) -> Void in
})
} else {

completionHandler(stateCode: .Success, error: nil, nextCursor: nextCursor)
}
}
})
}
})
}


// Model
static func friendsJSONToUserAndSave(json json: JSON, completionHandler: (stateCode: WeiboStoreError, error: String?, count: Int?) -> Void) {

var count = 0

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) {

let realm = try! Realm()
realm.beginWrite()

if json["users"] != JSON.null {

for (_, subJson): (String, JSON) in json["users"] {
let friend = self.JSONToUserModel(subJson)
friend.isFriend = true
realm.add(friend, update: true)

count += 1
}
}

do {
try realm.commitWrite()
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(stateCode: .Success, error: nil, count: count)
})
} catch {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(stateCode: .Error, error: "Realm Database save error.", count: nil)
})
}
}
}

The Swift Programming Language Examples

源码在 GitHub:https://github.com/gewill/The-Swift-Programming-Language-2.1-Examples

Playground ->

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// : Playground - noun: a place where people can play

import UIKit

//: 嵌套类型(Nested Types)



//嵌套让我们可以为常数生成一个命名空间(namespace)。例如:我们可以使用Constants.FoursquareApi.BaseUrl来访问Foursquare的BaseUrl常数,这样会使得数据可读性更高,并为相关的常数提供一系列封装。
//http://geek.csdn.net/news/detail/58593
import Foundation
struct Constants {
struct FoursquareApi {
static let BaseUrl = "https://api.foursquare.com/v2/"
}
struct TwitterApi {
static let BaseUrl = "https://api.twitter.com/1.1/"
}
struct Configuration {
static let UseWorkaround = true
}
}


//上面的嵌套是不错的实践,当然扑克牌作为例子是非常合适的。

struct BlackjackCard {
// 嵌套的 Suit 枚举
enum Suit: Character {
case Spades = "♠", Hearts = "♡", Diamonds = "♢", Clubs = "♣"
}

// 嵌套的 Rank 枚举
enum Rank: Int {
case Two = 2, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King, Ace
struct Values {
let first: Int, second: Int?
}
var values: Values {
switch self {
case .Ace:
return Values(first: 1, second: 11)
case .Jack, .Queen, .King:
return Values(first: 10, second: nil)
default:
return Values(first: self.rawValue, second: nil)
}
}
}

// BlackjackCard 的属性和方法
let rank: Rank, suit: Suit
var description: String {
var output = "suit is \(suit.rawValue),"
output += " value is \(rank.values.first)"
if let second = rank.values.second {
output += " or \(second)"
}
return output
}
}

BlackjackCard(rank: .Ace, suit: .Spades).description
let heartsSymbol = BlackjackCard.Suit.Hearts.rawValue

The Swift Programming Language Examples

源码在 GitHub:https://github.com/gewill/The-Swift-Programming-Language-2.1-Examples

Playground ->

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// : Playground - noun: a place where people can play

import UIKit

//: 错误处理(Error Handling)

//说实话错误处理这里,习惯了 AFNetworking 方式的闭包或者 block。因为闭包可以返回更过参数如:错误类型/错误内容/其他参数
//这里学会三种调用方法即可,try? 最方便,如不打算考虑处理错误信息


enum VendingMachineError: ErrorType {
case InvalidSelection //选择无效
case InsufficientFunds(coinsNeeded: Int) //金额不足
case OutOfStock //缺货
}


struct Item {
var price: Int
var count: Int
}

class VendingMachine {
var inventory = [
"Candy Bar": Item(price: 12, count: 7),
"Chips": Item(price: 10, count: 4),
"Pretzels": Item(price: 7, count: 11)
]
var coinsDeposited = 0
func dispenseSnack(snack: String) {
print("Dispensing \(snack)")
}

func vend(itemNamed name: String) throws {
guard var item = inventory[name] else {
throw VendingMachineError.InvalidSelection
}

guard item.count > 0 else {
throw VendingMachineError.OutOfStock
}

guard item.price <= coinsDeposited else {
throw VendingMachineError.InsufficientFunds(coinsNeeded: item.price - coinsDeposited)
}

coinsDeposited -= item.price
--item.count
inventory[name] = item
dispenseSnack(name)
}
}

let favoriteSnacks = [
"Alice": "Chips",
"Bob": "Licorice",
"Eve": "Pretzels",
]
func buyFavoriteSnack(person: String, vendingMachine: VendingMachine) throws {
let snackName = favoriteSnacks[person] ?? "Candy Bar"
try vendingMachine.vend(itemNamed: snackName)
}

//: 用 Do-Catch 处理错误
var vendingMachine = VendingMachine()
vendingMachine.coinsDeposited = 8
do {
try buyFavoriteSnack("Alice", vendingMachine: vendingMachine)
} catch VendingMachineError.InvalidSelection {
print("Invalid Selection.")
} catch VendingMachineError.OutOfStock {
print("Out of Stock.")
} catch VendingMachineError.InsufficientFunds(let coinsNeeded) {
print("Insufficient funds. Please insert an additional \(coinsNeeded) coins.")
}
// 打印 “Insufficient funds. Please insert an additional 2 coins.”


//: 将错误转换成可选值

func fetchData() -> Data? {
if let data = try? fetchDataFromDisk() { return data }
if let data = try? fetchDataFromServer() { return data }
return nil
}

//: 禁用错误传递

//有时你知道某个 throwing 函数实际上在运行时是不会抛出错误的,在这种情况下,你可以在表达式前面写try!来禁用错误传递,这会把调用包装在一个断言不会有错误抛出的运行时断言中。如果实际上抛出了错误,你会得到一个运行时错误。

//例如,下面的代码使用了loadImage(_:)函数,该函数从给定的路径加载图片资源,如果图片无法载入则抛出一个错误。在这种情况下,因为图片是和应用绑定的,运行时不会有错误抛出,所以适合禁用错误传递:

let photo = try! loadImage("./Resources/John Appleseed.jpg")

//: 指定清理操作
//可以使用defer语句在即将离开当前代码块时执行一系列语句。

func processFile(filename: String) throws {
if exists(filename) {
let file = open(filename)
defer {
close(file)
}
while let line = try file.readline() {
// 处理文件。
}
// close(file) 会在这里被调用,即作用域的最后。
}
}


The Swift Programming Language Examples

源码在 GitHub:https://github.com/gewill/The-Swift-Programming-Language-2.1-Examples

Playground ->

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
// : Playground - noun: a place where people can play

import UIKit

//: 自动引用计数(Automatic Reference Counting)

//自动引用计数实践
class Person0 {
let name: String
init(name: String) {
self.name = name
print("\(name) is being initialized")
}
deinit {
print("\(name) is being deinitialized")
}
}

var reference1: Person0?
var reference2: Person0?
var reference3: Person0?

reference1 = Person0(name: "John Appleseed")

reference2 = reference1
reference3 = reference1

reference1 = nil
reference2 = nil

reference3 = nil

//: 解决实例之间的循环强引用

//Swift 提供了两种办法用来解决你在使用类的属性时所遇到的循环强引用问题:弱引用(weak reference)和无主引用(unowned reference)。

//弱引用和无主引用允许循环引用中的一个实例引用另外一个实例而不保持强引用。这样实例能够互相引用而不产生循环强引用。

//对于生命周期中会变为nil的实例使用弱引用。相反地,对于初始化赋值后再也不会被赋值为nil的实例,使用无主引用。

//和弱引用类似,无主引用不会牢牢保持住引用的实例。和弱引用不同的是,无主引用是永远有值的。因此,无主引用总是被定义为非可选类型(non-optional type)。你可以在声明属性或者变量时,在前面加上关键字unowned表示这是一个无主引用。

//: 1 - Person和Apartment的例子展示了两个属性的值都允许为nil,并会潜在的产生循环强引用。这种场景最适合用弱引用来解决。
class Person {
let name: String
init(name: String) { self.name = name }
var apartment: Apartment?
deinit { print("\(name) is being deinitialized") }
}
class Apartment {
let unit: String
init(unit: String) { self.unit = unit }
weak var tenant: Person?
deinit { print("Apartment \(unit) is being deinitialized") }
}

var john: Person?
var unit4A: Apartment?

john = Person(name: "John Appleseed")
unit4A = Apartment(unit: "4A")

john!.apartment = unit4A
unit4A!.tenant = john

john = nil
unit4A = nil

//: 2 - Customer和CreditCard的例子展示了一个属性的值允许为nil,而另一个属性的值不允许为nil,这也可能会产生循环强引用。这种场景最适合通过无主引用来解决。
class Customer {
let name: String
var card: CreditCard?
init(name: String) {
self.name = name
}
deinit { print("\(name) is being deinitialized") }
}
class CreditCard {
let number: UInt64
unowned let customer: Customer
init(number: UInt64, customer: Customer) {
self.number = number
self.customer = customer
}
deinit { print("Card #\(number) is being deinitialized") }
}

var lee: Customer?
lee = Customer(name: "Brunce Lee")
let card = CreditCard(number: 1234567890123456, customer: lee!)
lee = nil
card

//: 3 - 两个属性都必须有值,并且初始化完成后永远不会为nil。在这种场景中,需要一个类使用无主属性,而另外一个类使用隐式解析可选属性。

class Country {
let name: String
var capitalCity: City!
init(name: String, capitalName: String) {
self.name = name
self.capitalCity = City(name: capitalName, country: self)
}
}
class City {
let name: String
unowned let country: Country
init(name: String, country: Country) {
self.name = name
self.country = country
}
}

var country: Country?
country = Country(name: "Canada", capitalName: "Ottawa")
print("\(country!.name)'s capital city is called \(country!.capitalCity.name)")
country = nil

//: 解决闭包引起的循环强引用

//在定义闭包时同时定义捕获列表作为闭包的一部分,通过这种方式可以解决闭包和类实例之间的循环强引用。

/*
lazy var someClosure: (Int, String) -> String = {
[unowned self, weak delegate = self.delegate!] (index: Int, stringToProcess: String) -> String in
// 这里是闭包的函数体
}
*/

class HTMLElement {

let name: String
let text: String?

lazy var asHTML: Void -> String = {
[unowned self] in
if let text = self.text {
return "<\(self.name)>\(text)</\(self.name)>"
} else {
return "<\(self.name) />"
}
}

init(name: String, text: String? = nil) {
self.name = name
self.text = text
}

deinit {
print("\(name) is being deinitialized")
}

}

var paragraph: HTMLElement? = HTMLElement(name: "p", text: "hello, world")
print(paragraph!.asHTML())
paragraph = nil



0%