I've tried the code below targeting both iOS 10.0/Watch OS 3.0 and iOS 11.0/Watch OS 4.0, and tested both in the simulator and my Watch OS 4 device. Nothing seems to trigger the crownDidRotate delegate method.
Simple interface with one label connected to the outlet. I know it's connected because I change the text in the awake method. Breaking in the delegate method never stops when I rotate the crown.
Any ideas?
import Foundation
import WatchKit
class InterfaceController: WKInterfaceController, WKCrownDelegate {
var value = 1
#IBOutlet var label: WKInterfaceLabel!
override func awake(withContext context: Any?) {
super.awake(withContext: context)
label.setText("Yeah?")
crownSequencer.delegate = self
crownSequencer.focus()
}
func crownDidRotate(_ crownSequencer: WKCrownSequencer?, rotationalDelta: Double) {
label.setText("Rotational: \(rotationalDelta)")
}
}
I had the same experience. As a hack, I added another call to crownSequencer.focus() in willActivate(), and I'm now seeing events. (xcode 9.0 gm, ios 11.0 gm, watchos 4.0 gm)
Adding crownSequencer.focus() in willActivate() did not help me in Xcode10.
You don't have to call crownSequencer.focus() neither in awake() or in willActivate() but in didAppear(). So you need to add the following lines:
override func didAppear() {
super.didAppear()
crownSequencer.focus()
}
Related
We are in advanced stages of developing a Swift2.2 app and hence have decided to migrate to 2.3 in the interim and do the full Swift 3 migration later. However we are unable to get beacon detection working post conversion to Swift 2.3. The method "didRangeBeacons" keeps returning an empty array. The same code was working in Swift 2.2 so we know we have all the permissions etc in place.
Also if we open the "Locate" app on the same ipad then our app also starts returning data in "didRangeBeacons". Have tried various versions of the apps out there and all Swift2.3 apps are behaving the same way. Can't make out what the Locate app is doing... Anyone on the same boat??
Here is the code we are using. Am not sure this is supposed to be written here or in comments but couldn't put code within comments somehow...
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
let region = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "9735BF2A-0BD1-4877-9A4E-103127349E1D")!, identifier: "testing")
// Note: make sure you replace the keys here with your own beacons' Minor Values
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.locationManager.delegate = self
self.locationManager.requestAlwaysAuthorization()
self.locationManager.startMonitoringForRegion(self.region)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didStartMonitoringForRegion region: CLRegion) {
print("didStartMonitoringForRegion")
self.locationManager.requestStateForRegion(region)
}
func locationManager(manager: CLLocationManager, monitoringDidFailForRegion region: CLRegion?, withError error: NSError) {
print("monitoringDidFailForRegion")
}
func locationManager(manager: CLLocationManager, didDetermineState state: CLRegionState, forRegion region: CLRegion) {
print("didDetermineState")
if state == .Inside {
//Start Ranging
self.locationManager.startRangingBeaconsInRegion(self.region)
self.locationManager.startUpdatingLocation()
}
else {
//Stop Ranging here
self.locationManager.stopUpdatingLocation()
self.locationManager.stopRangingBeaconsInRegion(self.region)
}
}
func locationManager(manager: CLLocationManager, didRangeBeacons beacons: [CLBeacon], inRegion region: CLBeaconRegion) {
print(beacons.count)
}
}
[Update post some more attempts to get this working]
App works in foreground mode if we remove self.locationManager.startMonitoringForRegion(self.region)
and call self.locationManager.startRangingBeaconsInRegion(self.region)
directly after self.locationManager.requestAlwaysAuthorization()
This is sub-optimal because we don't get entry and exit events or state but atleast we are getting beacon counts.
There are a number of anecdotal reports of beacon detection problems on iOS 10. Symptoms include:
Improper region exit events, especially when the app is in the background, followed by entry events if the shoulder button is pressed.
Periodic dropouts in detections of ranged beacons, with callbacks providing an empty beacon list when beacons are in the vicinity.
Ranged beacon callbacks return proper results when a different beacon ranging or detection app is running that targets iOS 9.x.
This is presumably a bug that will be fixed in an iOS update. Until then, some users have reported that setting the app deployment target in XCode to 9.x will resolve the issue.
Try constructing your location manager after the view loads. In other words, change:
let locationManager = CLLocationManager()
to
let locationManager : CLLocationManager!
And then add this to the viewDidLoad:
locationManager = CLLocationManager()
I have seen strange behavior with LocationManager constructed on initialization of a UIViewController.
While I was testing beacon ranging, I downloaded multiple applications that I forgot to uninstall. After I uninstalled all beacon-related applications and re-installed just the needed applications, I was able to get ranging beacons to work.
I am migrating an Xcode 7 / Swift 2.2 mac OS X project to Xcode 8 / Swift 3, and I have run into a problem using undoManager in my view controller class, MyViewController, which has a function undo.
In Xcode 7 / Swift 2.2, this worked fine:
undoManager?.prepareWithInvocationTarget(self).undo(data, moreData: moreData)
undoManager?.setActionName("Change Data)
In Xcode 8 / Swift 3, using the recommended pattern from https://developer.apple.com/library/content/documentation/Swift/Conceptual/BuildingCocoaApps/AdoptingCocoaDesignPatterns.html
this should be changed to:
if let target = undoManager?.prepare(withInvocationTarget: self) as? MyViewController {
target.undo(data, moreData: moreData)
undoManager?. setActionName("Change Data")
}
However, the downcast to MyViewController always fails, and the undo operation is not registered.
Am I missing something obvious here, or is this a bug?
prepareWithInvocationTarget(_:)(or prepare(withInvocationTarget:) in Swift 3) creates a hidden proxy object, with which Swift 3 runtime cannot work well.
(You may call that a bug, and send a bug report.)
To achieve your purpose, can't you use registerUndo(withTarget:handler:)?
undoManager?.registerUndo(withTarget: self) {targetSelf in
targetSelf.undo(data, moreData: moreData)
}
I've had the same issue and I wasn't prepared to drop iOS 8 and macOS 10.10 support or go back to Swift 2.3. The registerUndo(withTarget:handler) syntax is nice though, so I basically just rolled my own version of that:
/// An extension to undo manager that adds closure based
/// handling to OS versions where it is not available.
extension UndoManager
{
/// Registers an undo operation using a closure. Behaves in the same wasy as
/// `registerUndo(withTarget:handler)` but it compatible with older OS versions.
func compatibleRegisterUndo<TargetType : AnyObject>(withTarget target: TargetType, handler: #escaping (TargetType) -> ())
{
if #available(iOS 9.0, macOS 10.11, *)
{
self.registerUndo(withTarget: target, handler: handler)
}
else
{
let operation = BlockOperation {
handler(target)
}
self.registerUndo(withTarget: self, selector: #selector(UndoManager.performUndo(operation:)), object: operation)
}
}
/// Performs an undo operation after it has been registered
/// by `compatibleRegisterUndo`. Should not be called directly.
func performUndo(operation: Operation)
{
operation.start()
}
}
Hopefully it's helpful to someone else too.
Solution for backward compatibility with OS 10.10: use registerUndo(with Target: selector: object: ). No problem for saving single value. To save multiple values, I pack them into a dictionary and use that for the "object" parameter. For the undo operation, I unpack them from the dictionary, and then call the OS10.11+ undo method with those values.
What I am trying to do
I want to run a daemon process that can listen to OSX system events like NSWorkspaceWillLaunchApplicationNotification in an command line tool xcode project? Is that possible? And if not, why not and are there any work arounds or hacks?
Some code samples
The following sample code from a swift 2 cocoa application project sets up a system event listener, which calls WillLaunchApp every time an OSX app gets started. (this works just fine)
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
NSWorkspace.sharedWorkspace()
.notificationCenter.addObserver(self,
selector: "WillLaunchApp:",
name: NSWorkspaceWillLaunchApplicationNotification, object: nil)
}
func WillLaunchApp(notification: NSNotification!) {
print(notification)
}
}
In contrast this simingly similar swift 2 command line tool project will not call WillLaunchApp.
import Cocoa
class MyObserver: NSObject
{
override init() {
super.init()
NSWorkspace.sharedWorkspace()
.notificationCenter.addObserver(self,
selector: "WillLaunchApp:",
name: NSWorkspaceWillLaunchApplicationNotification, object: nil)
}
func WillLaunchApp(notification: NSNotification!) {
// is never called
print(notification)
}
}
let observer = MyObserver()
while true {
// simply to keep the command line tool alive - as a daemon process
sleep(1)
}
I am guessing I am missing some cocoa and/or xcode fundamentals here, but I cannot figure out which ones. Maybe it is related to the while-true loop, which might be blocking the events. If so, is there a correct way to run a daemon process?
It turns out using while true loop does block the main-thread.
Simply replace the while true loop with NSRunLoop.mainRunLoop().run() and you have a daemon process.
I read the sources of swifter (a swift-based server), which is doing the same.
In Swift 3 and later, the equivalent code is:
RunLoop.main.run()
I am following the cocoa documentation to determine the current front most application in OSX - aka the application which receives key events.
However, when I am executing the following swift the API always returns me the same value - XCode, but it never changes to chrome or any other application when I switch to them. I also tried to execute the compiled program but instead of constantly showing XCode it now shows whichever terminal app I am running.
What is the correct way of determining the application that receives the key events from OSX? Is my code in this regard broken?
import Cocoa
func getActiveApplication() -> String{
// Return the localized name of the currently active application
let ws = NSWorkspace.sharedWorkspace()
let frontApp = ws.frontmostApplication
return frontApp.localizedName
}
var frontMostApp : String
while true {
frontMostApp = getActiveApplication();
NSLog("front app: %#", frontMostApp)
sleep(1);
}
This thread is a bit old but was very helpful. I did some research based on Marco's post and uchuugaka's answer. The following is the result.
// swift 3.0
// compile: xcrun -sdk macosx swiftc -framework Cocoa foo.swift -o foo
// run: ./foo
import Cocoa
class MyObserver: NSObject {
override init() {
super.init()
NSWorkspace.shared().notificationCenter.addObserver(self,
selector: #selector(printMe(_:)),
name: NSNotification.Name.NSWorkspaceDidActivateApplication,
object:nil)
}
dynamic private func printMe(_ notification: NSNotification) {
let app = notification.userInfo!["NSWorkspaceApplicationKey"] as! NSRunningApplication
print(app.localizedName!)
}
}
let observer = MyObserver()
RunLoop.main.run()
I am a newbie in both Cocoa and Swift. I don't know if the above is efficient, but it works for me. I got help from How to create a minimal daemon process in a swift 2 command line tool? and Swift 3 NSNotificationCenter Keyboardwillshow/hide among numerous others.
Swift 4:
NSWorkspace.shared.notificationCenter.addObserver(self, // HERE, shared
selector: #selector(printMe(_:)),
name: NSWorkspace.didActivateApplicationNotification, // HERE
object:nil)
Edit (Swift 4)
The compiler says the printMe function must be #objc. (I don't know the meaning, but it worked when I prepend #objc at the beginning of the line. Here is the full code for easy copy-paste.
// swift 4.0
// compile: xcrun -sdk macosx swiftc -framework Cocoa foo.swift -o foo
// run: ./foo
import Cocoa
class MyObserver: NSObject {
override init() {
super.init()
NSWorkspace.shared.notificationCenter.addObserver(self,
selector: #selector(printMe(_:)),
name: NSWorkspace.didActivateApplicationNotification,
object:nil)
}
#objc dynamic private func printMe(_ notification: NSNotification) {
let app = notification.userInfo!["NSWorkspaceApplicationKey"] as! NSRunningApplication
print(app.localizedName!)
}
}
let observer = MyObserver()
RunLoop.main.run()
You you should do one thing differently, that is follow the NSWorkSpace notifications that tell you the applications resigned active or became active.
This is key especially as you are running in debug mode.
In debug mode Xcode is spawning your app as a child process.
In release mode it is basically doing the same as calling the open command in terminal.
In debug mode if you call this code too early and only once, you're not catching changes. Remember it's dynamic.
I am with Xcode beta 2 and trying to get user location with OS X app, however it is not even asks user permission. here is what I did until now.
...
import CoreLocation
class AppDelegate: NSObject, NSApplicationDelegate, CLLocationManagerDelegate {
var locManager : CLLocationManager = CLLocationManager()
func applicationDidFinishLaunching(aNotification: NSNotification?) {
locManager.delegate = self
locManager.desiredAccuracy = kCLLocationAccuracyBest
locManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateToLocation newLocation: CLLocation!, fromLocation oldLocation: CLLocation!) {
//doSomething.
}
}
nothing happens. I looked other questions and try all suggested solutions from answers but did not work. Tried with Objective-C, all fine. Am I missing something here?
Location Service enabled on preferences of the computer. Also "NSLocationUsageDescription" is in info.plist. NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription for 10.10 and later, I am working on 10.9.
Information Property List Key Reference
There were no problem code wise, just noticed it is App Sandbox entitlement problem. Once I have checked Location under App Data it worked right away.