Skip to content

'Cancel' for PromiseKit #20

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cartfile
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
github "mxcl/PromiseKit" ~> 6.0
#github "mxcl/PromiseKit" ~> 6.0
github "dougzilla32/PromiseKit" "CoreCancel"
2 changes: 1 addition & 1 deletion Cartfile.resolved
Original file line number Diff line number Diff line change
@@ -1 +1 @@
github "mxcl/PromiseKit" "6.3.3"
github "dougzilla32/PromiseKit" "087b3cf470890ff9ea841212e2f3e285fecf3988"
27 changes: 25 additions & 2 deletions Sources/CLLocationManager+Promise.swift
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ extension CLLocationManager {
- Returns: A new promise that fulfills with the most recent CLLocation that satisfies
the provided block if it exists. If the block does not exist, simply return the
last location.
- Note: cancelling this promise will cancel the underlying task
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
public class func requestLocation(authorizationType: RequestAuthorizationType = .automatic, satisfying block: ((CLLocation) -> Bool)? = nil) -> Promise<[CLLocation]> {

Expand Down Expand Up @@ -97,7 +99,7 @@ extension CLLocationManager {
}
}

private class LocationManager: CLLocationManager, CLLocationManagerDelegate {
private class LocationManager: CLLocationManager, CLLocationManagerDelegate, CancellableTask {
let (promise, seal) = Promise<[CLLocation]>.pending()
let satisfyingBlock: ((CLLocation) -> Bool)?

Expand All @@ -120,6 +122,9 @@ private class LocationManager: CLLocationManager, CLLocationManagerDelegate {
satisfyingBlock = block
super.init()
delegate = self

promise.setCancellableTask(self, reject: seal.reject)

#if !os(tvOS)
startUpdatingLocation()
#else
Expand All @@ -138,6 +143,13 @@ private class LocationManager: CLLocationManager, CLLocationManagerDelegate {
seal.reject(error)
}
}

func cancel() {
self.stopUpdatingLocation()
isCancelled = true
}

var isCancelled = false
}


Expand All @@ -148,6 +160,8 @@ extension CLLocationManager {
Request CoreLocation authorization from the user
- Note: By default we try to determine the authorization type you want by inspecting your Info.plist
- Note: This method will not perform upgrades from “when-in-use” to “always” unless you specify `.always` for the value of `type`.
- Note: cancelling this promise will cancel the underlying task
- SeeAlso: [Cancellation](http://promisekit.org/docs/)
*/
@available(iOS 8, tvOS 9, watchOS 2, *)
public class func requestAuthorization(type requestedAuthorizationType: RequestAuthorizationType = .automatic) -> Guarantee<CLAuthorizationStatus> {
Expand Down Expand Up @@ -203,14 +217,16 @@ extension CLLocationManager {
}

@available(iOS 8, *)
private class AuthorizationCatcher: CLLocationManager, CLLocationManagerDelegate {
private class AuthorizationCatcher: CLLocationManager, CLLocationManagerDelegate, CancellableTask {
let (promise, fulfill) = Guarantee<CLAuthorizationStatus>.pending()
var retainCycle: AuthorizationCatcher?
let initialAuthorizationState = CLLocationManager.authorizationStatus()

init(type: PMKCLAuthorizationType) {
super.init()

promise.setCancellableTask(self)

func ask(type: PMKCLAuthorizationType) {
delegate = self
retainCycle = self
Expand Down Expand Up @@ -263,6 +279,13 @@ private class AuthorizationCatcher: CLLocationManager, CLLocationManagerDelegate
fulfill(status)
}
}

func cancel() {
self.retainCycle = nil
isCancelled = true
}

var isCancelled = false
}

#endif
Expand Down
114 changes: 114 additions & 0 deletions Tests/CLGeocoderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -100,3 +100,117 @@ class CLGeocoderTests: XCTestCase {
}

private let dummyPlacemark = CLPlacemark()

//////////////////////////////////////////////////////////// Cancellation

extension CLGeocoderTests {
func testCancel_reverseGeocodeLocation() {
class MockGeocoder: CLGeocoder {
override func reverseGeocodeLocation(_ location: CLLocation, completionHandler: @escaping CLGeocodeCompletionHandler) {
after(.milliseconds(100)).done {
completionHandler([dummyPlacemark], nil)
}
}
}

let ex = expectation(description: "")
cancellable(MockGeocoder().reverseGeocode(location: CLLocation())).done { _ in
XCTFail("not cancelled")
}.catch(policy: .allErrors) { error in
error.isCancelled ? ex.fulfill() : XCTFail("error \(error)")
}.cancel()

waitForExpectations(timeout: 1)
}

func testCancel_geocodeAddressDictionary() {
class MockGeocoder: CLGeocoder {
override func geocodeAddressDictionary(_ addressDictionary: [AnyHashable: Any], completionHandler: @escaping CLGeocodeCompletionHandler) {
after(.milliseconds(100)).done {
completionHandler([dummyPlacemark], nil)
}
}
}

let ex = expectation(description: "")
let context = cancellable(MockGeocoder().geocode([:])).done { _ in
XCTFail("not cancelled")
}.catch(policy: .allErrors) { error in
error.isCancelled ? ex.fulfill() : XCTFail("error \(error)")
}.cancelContext
after(.milliseconds(50)).done {
context.cancel()
}

waitForExpectations(timeout: 1)
}

func testCancel_geocodeAddressString() {
class MockGeocoder: CLGeocoder {
override func geocodeAddressString(_ addressString: String, completionHandler: @escaping CLGeocodeCompletionHandler) {
after(.milliseconds(100)).done {
completionHandler([dummyPlacemark], nil)
}
}
}

let ex = expectation(description: "")
let p = cancellable(MockGeocoder().geocode("")).done { _ in
XCTFail("not cancelled")
}.catch(policy: .allErrors) { error in
error.isCancelled ? ex.fulfill() : XCTFail("error \(error)")
}
after(.milliseconds(50)).done {
p.cancel()
}
waitForExpectations(timeout: 1)
}

#if !os(tvOS) && swift(>=3.2)
func testCancel_geocodePostalAddress() {
guard #available(iOS 11.0, OSX 10.13, watchOS 4.0, *) else { return }

class MockGeocoder: CLGeocoder {
override func geocodePostalAddress(_ postalAddress: CNPostalAddress, completionHandler: @escaping CLGeocodeCompletionHandler) {
after(.milliseconds(100)).done {
completionHandler([dummyPlacemark], nil)
}
}
}

let ex = expectation(description: "")
let p = cancellable(MockGeocoder().geocodePostalAddress(CNPostalAddress())).done { _ in
XCTFail("not cancelled")
}.catch(policy: .allErrors) { error in
error.isCancelled ? ex.fulfill() : XCTFail("error \(error)")
}
after(.milliseconds(50)).done {
p.cancel()
}
waitForExpectations(timeout: 1)
}

func testCancel_geocodePostalAddressLocale() {
guard #available(iOS 11.0, OSX 10.13, watchOS 4.0, *) else { return }

class MockGeocoder: CLGeocoder {
override func geocodePostalAddress(_ postalAddress: CNPostalAddress, preferredLocale locale: Locale?, completionHandler: @escaping CLGeocodeCompletionHandler) {
after(.milliseconds(100)).done {
completionHandler([dummyPlacemark], nil)
}
}
}

let ex = expectation(description: "")
let p = cancellable(MockGeocoder().geocodePostalAddress(CNPostalAddress(), preferredLocale: nil)).done { _ in
XCTFail("not cancelled")
}.catch(policy: .allErrors) { error in
error.isCancelled ? ex.fulfill() : XCTFail("error \(error)")
}
after(.milliseconds(50)).done {
p.cancel()
}
waitForExpectations(timeout: 1)
}
#endif
}
57 changes: 57 additions & 0 deletions Tests/CLLocationManagerTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,63 @@ class Test_CLLocationManager_Swift: XCTestCase {
#endif
}

//////////////////////////////////////////////////////////// Cancellation

extension Test_CLLocationManager_Swift {
func testCancel_fulfills_with_multiple_locations() {
swizzle(CLLocationManager.self, #selector(CLLocationManager.startUpdatingLocation)) {
swizzle(CLLocationManager.self, #selector(CLLocationManager.authorizationStatus), isClassMethod: true) {
let ex = expectation(description: "")

let p = cancellable(CLLocationManager.requestLocation()).done { _ in
XCTFail("not cancelled")
}.catch(policy: .allErrors) { error in
error.isCancelled ? ex.fulfill() : XCTFail("error \(error)")
}
after(.milliseconds(50)).done {
p.cancel()
}

waitForExpectations(timeout: 1)
}
}
}

func testCancel_fufillsWithSatisfyingBlock() {
swizzle(CLLocationManager.self, #selector(CLLocationManager.startUpdatingLocation)) {
swizzle(CLLocationManager.self, #selector(CLLocationManager.authorizationStatus), isClassMethod: true) {
let ex = expectation(description: "")
let block: ((CLLocation) -> Bool) = { location in
return location.coordinate.latitude == dummy.last?.coordinate.latitude
}
let p = cancellable(CLLocationManager.requestLocation(satisfying: block)).done { _ in
XCTFail("not cancelled")
}.catch(policy: .allErrors) { error in
error.isCancelled ? ex.fulfill() : XCTFail("error \(error)")
}
after(.milliseconds(50)).done {
p.cancel()
}
waitForExpectations(timeout: 1)
}
}
}

#if os(iOS)
func testCancel_requestAuthorization() {
let ex = expectation(description: "")

let p = cancellable(CLLocationManager.requestAuthorization()).done { _ in
XCTFail("not cancelled")
}.catch(policy: .allErrors) { error in
error.isCancelled ? ex.fulfill() : XCTFail("error \(error)")
}
p.cancel()

waitForExpectations(timeout: 1, handler: nil)
}
#endif
}

/////////////////////////////////////////////////////////////// resources
private let dummy = [CLLocation(latitude: 0, longitude: 0), CLLocation(latitude: 10, longitude: 20)]
Expand Down