Skip to content

Commit

Permalink
updated chapter 22 examples
Browse files Browse the repository at this point in the history
  • Loading branch information
mattneub committed Oct 8, 2016
1 parent cab0944 commit 4c226da
Show file tree
Hide file tree
Showing 17 changed files with 146 additions and 115 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class CancelableTimer: NSObject {
self.firsttime = true
self.cancel()
self.timer = DispatchSource.makeTimerSource(queue: self.q)
self.timer.scheduleRepeating(wallDeadline: DispatchWallTime.now(), interval: interval)
self.timer.scheduleRepeating(wallDeadline: .now(), interval: interval)
// self.timer.scheduleRepeating(deadline: .now(), interval: 1, leeway: .milliseconds(1))
self.timer.setEventHandler {
if self.firsttime {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@
ORGANIZATIONNAME = "Matt Neuburg";
TargetAttributes = {
32315063182E903500B03F54 = {
DevelopmentTeam = W3LHX5RGV2;
LastSwiftMigration = 0800;
SystemCapabilities = {
com.apple.BackgroundModes = {
Expand Down Expand Up @@ -237,6 +238,7 @@
ARCHS = "$(ARCHS_STANDARD)";
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
DEVELOPMENT_TEAM = W3LHX5RGV2;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "ch35p1032location/ch35p1032location-Prefix.pch";
INFOPLIST_FILE = "ch35p1032location/ch35p1032location-Info.plist";
Expand All @@ -255,6 +257,7 @@
ARCHS = "$(ARCHS_STANDARD)";
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
DEVELOPMENT_TEAM = W3LHX5RGV2;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "ch35p1032location/ch35p1032location-Prefix.pch";
INFOPLIST_FILE = "ch35p1032location/ch35p1032location-Info.plist";
Expand Down
125 changes: 69 additions & 56 deletions bk2ch22p773location/ch35p1032location/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,93 +2,105 @@
import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {
lazy var locman : CLLocationManager = {
let locman = CLLocationManager()
locman.delegate = self
return locman
}()
var startTime : Date!
var trying = false
class ManagerHolder {
let locman = CLLocationManager()
var delegate : CLLocationManagerDelegate? {
get {
return self.locman.delegate
}
set {
// set delegate _once_
if self.locman.delegate == nil && newValue != nil {
self.locman.delegate = newValue
print("setting delegate!")
}
}
}
var doThisWhenAuthorized : (() -> ())?

@discardableResult
func determineStatus() -> Bool {
func checkForLocationAccess(always:Bool = false, andThen f: (()->())? = nil) {
// no services? fail but try get alert
guard CLLocationManager.locationServicesEnabled() else {
self.locman.startUpdatingLocation() // might get "enable" dialog
return false
print("no location services")
self.locman.startUpdatingLocation()
return
}
let status = CLLocationManager.authorizationStatus()
switch status {
case .authorizedAlways, .authorizedWhenInUse:
return true
f?()
case .notDetermined:
self.locman.requestWhenInUseAuthorization()
// locman.requestAlwaysAuthorization()
return false
self.doThisWhenAuthorized = f
always ?
self.locman.requestAlwaysAuthorization() :
self.locman.requestWhenInUseAuthorization()
case .restricted:
return false
// do nothing
break
case .denied:
let message = "Wouldn't you like to authorize" +
"this app to use Location Services?"
let alert = UIAlertController(title: "Need Authorization", message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "No", style: .cancel))
alert.addAction(UIAlertAction(title: "OK", style: .default) {
_ in
let url = URL(string:UIApplicationOpenSettingsURLString)!
UIApplication.shared.open(url)
})
self.present(alert, animated:true)
return false
print("denied")
// do nothing, or beg the user to authorize us in Settings
break
}
}
}



class ViewController: UIViewController, CLLocationManagerDelegate {
let managerHolder = ManagerHolder()
var locman : CLLocationManager {
return self.managerHolder.locman
}

required init?(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
self.managerHolder.delegate = self
}

var startTime : Date!
var trying = false

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("did change auth: \(status.rawValue)")
switch status {
case .authorizedAlways, .authorizedWhenInUse:
self.doThisWhenAuthorized?()
self.managerHolder.doThisWhenAuthorized?()
self.managerHolder.doThisWhenAuthorized = nil
default: break
}
}

let which = 2 // 1 is old way, 2 is new way
let which = 2 // 1 or 2

@IBAction func doFindMe (_ sender: Any!) {
self.doThisWhenAuthorized = {
[unowned self] in
print("resuming")
self.doFindMe(sender)
}
guard self.determineStatus() else {
print("not authorized")
return
}
self.doThisWhenAuthorized = nil

switch which {
case 1:
if self.trying { return }
self.trying = true
self.locman.desiredAccuracy = kCLLocationAccuracyBest
self.locman.activityType = .fitness
self.startTime = nil
print("starting")
self.locman.startUpdatingLocation()
case 2:
self.locman.desiredAccuracy = kCLLocationAccuracyBest
self.locman.requestLocation()
default: break
self.managerHolder.checkForLocationAccess {
switch self.which {
case 1:
if self.trying { return }
self.trying = true
self.locman.desiredAccuracy = kCLLocationAccuracyBest
self.locman.activityType = .fitness
self.startTime = nil
print("starting")
self.locman.startUpdatingLocation()
case 2:
print("requesting")
self.locman.desiredAccuracy = kCLLocationAccuracyBest
self.locman.requestLocation()
default: break
}
}
}



func stopTrying () {
self.locman.stopUpdatingLocation()
self.startTime = nil
self.trying = false
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: NSError) {
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("failed: \(error)")
self.stopTrying()
}
Expand Down Expand Up @@ -125,6 +137,7 @@ class ViewController: UIViewController, CLLocationManagerDelegate {
let loc = locations.last!
let coord = loc.coordinate
print("The quick way: You are at \(coord.latitude) \(coord.longitude)")
// bug: can be called twice in quick succession
default: break
}
}
Expand Down
3 changes: 3 additions & 0 deletions bk2ch22p775heading/ch35p1035heading.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@
ORGANIZATIONNAME = "Matt Neuburg";
TargetAttributes = {
3228D8A9182ED6DD00EBC319 = {
DevelopmentTeam = W3LHX5RGV2;
LastSwiftMigration = 0800;
SystemCapabilities = {
com.apple.BackgroundModes = {
Expand Down Expand Up @@ -237,6 +238,7 @@
ARCHS = "$(ARCHS_STANDARD)";
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
DEVELOPMENT_TEAM = W3LHX5RGV2;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "ch35p1035heading/ch35p1035heading-Prefix.pch";
INFOPLIST_FILE = "ch35p1035heading/ch35p1035heading-Info.plist";
Expand All @@ -255,6 +257,7 @@
ARCHS = "$(ARCHS_STANDARD)";
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
DEVELOPMENT_TEAM = W3LHX5RGV2;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "ch35p1035heading/ch35p1035heading-Prefix.pch";
INFOPLIST_FILE = "ch35p1035heading/ch35p1035heading-Info.plist";
Expand Down
16 changes: 7 additions & 9 deletions bk2ch22p775heading/ch35p1035heading/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,14 @@ import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {

@IBOutlet var lab : UILabel!
lazy var locman : CLLocationManager = {
let locman = CLLocationManager()
locman.delegate = self
return locman
}()
let locman = CLLocationManager()
var updating = false

@IBAction func doStart (_ sender: Any!) {
guard CLLocationManager.headingAvailable() else {return} // lacking hardware
guard CLLocationManager.headingAvailable() else {return} // no hardware
if self.updating {return}
if self.locman.delegate == nil {self.locman.delegate = self}

print("starting")
self.locman.headingFilter = 5
self.locman.headingOrientation = .portrait
Expand All @@ -33,13 +31,13 @@ class ViewController: UIViewController, CLLocationManagerDelegate {
self.updating = false
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: NSError) {
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
self.doStop(nil)
}

func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {
var h = newHeading.magneticHeading
let h2 = newHeading.trueHeading // will be -1 if we have no location info
let h2 = newHeading.trueHeading // -1 if no location info
print("\(h) \(h2) ")
if h2 >= 0 {
h = h2
Expand All @@ -59,8 +57,8 @@ class ViewController: UIViewController, CLLocationManagerDelegate {
}

func locationManagerShouldDisplayHeadingCalibration(_ manager: CLLocationManager) -> Bool {
print("he asked me, he asked me")
return true // if you want the calibration dialog to be able to appear
// I did in fact see it appear, so this works in iOS 8.3 at least
}


Expand Down
3 changes: 3 additions & 0 deletions bk2ch22p780shake/ch35p1037shake.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@
ORGANIZATIONNAME = "Matt Neuburg";
TargetAttributes = {
32124890182F1AEF008CB25D = {
DevelopmentTeam = W3LHX5RGV2;
LastSwiftMigration = 0800;
};
};
Expand Down Expand Up @@ -232,6 +233,7 @@
ARCHS = "$(ARCHS_STANDARD)";
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
DEVELOPMENT_TEAM = W3LHX5RGV2;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "ch35p1037shake/ch35p1037shake-Prefix.pch";
INFOPLIST_FILE = "ch35p1037shake/ch35p1037shake-Info.plist";
Expand All @@ -250,6 +252,7 @@
ARCHS = "$(ARCHS_STANDARD)";
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
DEVELOPMENT_TEAM = W3LHX5RGV2;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "ch35p1037shake/ch35p1037shake-Prefix.pch";
INFOPLIST_FILE = "ch35p1037shake/ch35p1037shake-Info.plist";
Expand Down
4 changes: 2 additions & 2 deletions bk2ch22p780shake/ch35p1037shake/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class ViewController: UIViewController {
// shake device (or simulator), watch console for response
// note that this does not disable Undo by shaking in text field

override func canBecomeFirstResponder() -> Bool {
override var canBecomeFirstResponder : Bool {
return true
}

Expand All @@ -16,7 +16,7 @@ class ViewController: UIViewController {
}

override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if self.isFirstResponder() {
if self.isFirstResponder {
print("hey, you shook me!")
} else {
super.motionEnded(motion, with: event)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@
ORGANIZATIONNAME = "Matt Neuburg";
TargetAttributes = {
321248D1182F1F25008CB25D = {
DevelopmentTeam = W3LHX5RGV2;
LastSwiftMigration = 0800;
};
};
Expand Down Expand Up @@ -232,6 +233,7 @@
ARCHS = "$(ARCHS_STANDARD)";
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
DEVELOPMENT_TEAM = W3LHX5RGV2;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "ch25p1039lyingDown/ch25p1039lyingDown-Prefix.pch";
INFOPLIST_FILE = "ch25p1039lyingDown/ch25p1039lyingDown-Info.plist";
Expand All @@ -250,6 +252,7 @@
ARCHS = "$(ARCHS_STANDARD)";
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
CLANG_ENABLE_MODULES = YES;
DEVELOPMENT_TEAM = W3LHX5RGV2;
GCC_PRECOMPILE_PREFIX_HEADER = YES;
GCC_PREFIX_HEADER = "ch25p1039lyingDown/ch25p1039lyingDown-Prefix.pch";
INFOPLIST_FILE = "ch25p1039lyingDown/ch25p1039lyingDown-Info.plist";
Expand Down
17 changes: 8 additions & 9 deletions bk2ch22p782lyingDown/ch25p1039lyingDown/ViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,22 +44,21 @@ class ViewController: UIViewController {
self.motman.startAccelerometerUpdates()
self.timer = Timer.scheduledTimer(timeInterval:self.motman.accelerometerUpdateInterval, target: self, selector: #selector(pollAccel), userInfo: nil, repeats: true)
case 2:
self.motman.startAccelerometerUpdates(to: .main) {
(accelerometerData:CMAccelerometerData?, error:NSError?) in
guard let dat = accelerometerData else {
print(error)
self.motman.startAccelerometerUpdates(to: .main) { data, err in
guard let data = data else {
print(err)
self.stopAccelerometer()
return
}
self.receive(acceleration:dat)
self.receive(acceleration:data)
}
default:break
}
}

func pollAccel (_: Any!) {
guard let dat = self.motman.accelerometerData else {return}
self.receive(acceleration:dat)
guard let data = self.motman.accelerometerData else {return}
self.receive(acceleration:data)
}

func add(acceleration accel:CMAcceleration) {
Expand All @@ -69,8 +68,8 @@ class ViewController: UIViewController {
self.oldZ = accel.z * alpha + self.oldZ * (1.0 - alpha)
}

func receive(acceleration dat:CMAccelerometerData) {
self.add(acceleration: dat.acceleration)
func receive(acceleration data:CMAccelerometerData) {
self.add(acceleration: data.acceleration)
let x = self.oldX
let y = self.oldY
let z = self.oldZ
Expand Down
Loading

0 comments on commit 4c226da

Please sign in to comment.