Is there any API available for Apple Watch Kit sensors such as the accelerometer, heart rate monitor, haptic sensor ?
How can I access those sensors ?
Sensor Data (accelerometer, heart rate monitor, haptic sensor) information is now available in Watchkit for watchOS 2.0.
You could check this information in the following session which is total 30 minutes presentation.If you do not want to watch entire session, then you directly jump to the CoreMotion and HealthKit features which is in between 22-28 min:
WatchKit for watchOS 2.0 Session in WWDC 2015
Heart Rate Code
https://developer.apple.com/library/prerelease/watchos/documentation/HealthKit/Reference/HKWorkout_Class/
Accelerometer code
Here is the implementation of Accelerometer in WatchKit Extension, I have added three labels (LabelX, LabelY, and LabelZ) on watch storyboard.
import WatchKit
import Foundation
import CoreMotion
class InterfaceController: WKInterfaceController {
#IBOutlet weak var labelX: WKInterfaceLabel!
#IBOutlet weak var labelY: WKInterfaceLabel!
#IBOutlet weak var labelZ: WKInterfaceLabel!
let motionManager = CMMotionManager()
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
motionManager.accelerometerUpdateInterval = 0.1
}
override func willActivate() {
super.willActivate()
if (motionManager.accelerometerAvailable == true) {
let handler:CMAccelerometerHandler = {(data: CMAccelerometerData?, error: NSError?) -> Void in
self.labelX.setText(String(format: "%.2f", data!.acceleration.x))
self.labelY.setText(String(format: "%.2f", data!.acceleration.y))
self.labelZ.setText(String(format: "%.2f", data!.acceleration.z))
}
motionManager.startAccelerometerUpdatesToQueue(NSOperationQueue.currentQueue()!, withHandler: handler)
}
else {
self.labelX.setText("not available")
self.labelY.setText("not available")
self.labelZ.setText("not available")
}
}
override func didDeactivate() {
super.didDeactivate()
motionManager.stopAccelerometerUpdates()
}
}
There is no current available option to access any sensor of the Apple Watch with the current version of the WatchKit SDK.
Related
I'm using Swift 4 and Xcode 9.2 to build a timer app and I'm running into issues with macOS App Nap. I know that the issues are caused by App Nap since when I disable App Nap globally the issues go away. However I only want to disable App Nap for this particular app when I need to for it to run properly. I know that similar questions have been answered before and I have seen them, but either I don't understand how to use them in my case or they do not work anymore (possibly because of changes to the Swift language).
Here is a small example of code that produces the issues I'm having:
import Cocoa
#NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
#IBOutlet weak var window: NSWindow!
var timer = Timer()
var seconds = 300
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Insert code here to initialize your application
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
#IBAction func goButton(_ sender: NSButton) {
if !timer.isValid {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(AppDelegate.ticker), userInfo: nil, repeats: true)
}
}
#objc func ticker() {
seconds -= 1
if seconds == 0 {
timer.invalidate()
print("Timer Ended.")
}
}
}
Any help is greatly appreciated.
I'm a beginner on TVOS.
I'd like to create an hybrid app on AppleTV using a native app and TVMLKIT.
My native application is just a simple native app with buttons (using swift).
When we click on a button, I launch a a javascript app using TVLMKIT and TVJS.
My TVJS as uses the Player to display a video.
When the video is over, I want to close the TVJS app and back to the native ViewController.
My problem is that when I back to native app, I loose the focus on my native View (the app is frozen).
native ViewController:
import UIKit
import TVMLKit
class ViewController: UIViewController, TVApplicationControllerDelegate {
var window: UIWindow?
var appController: TVApplicationController?
var appControllerContext = TVApplicationControllerContext();
static let TVBaseURL = "http://localhost:9001/"
static let TVBootURL = "\(ViewController.TVBaseURL)/client/js/application.js"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBOutlet weak var label: UILabel!
#IBOutlet weak var viewAd: UIView!
#IBAction func clickOnlaunchAd(sender: AnyObject) {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
guard let javaScriptURL = NSURL(string: ViewController.TVBootURL) else {
fatalError("unable to create NSURL")
}
appControllerContext.javaScriptApplicationURL = javaScriptURL
appControllerContext.launchOptions["BASEURL"] = ViewController.TVBaseURL
appController = TVApplicationController(context: appControllerContext, window: window,delegate: self)
}
#IBAction func clickOnChangeText(sender: AnyObject) {
label.text = "changed";
}
func appController(appController: TVApplicationController, didStopWithOptions options: [String : AnyObject]?) {
self.setNeedsFocusUpdate()
self.updateFocusIfNeeded()
}
func appController(appController: TVApplicationController, evaluateAppJavaScriptInContext jsContext: JSContext){
let notifyEventToNative : #convention(block) (NSString!) -> Void = {
(string : NSString!) -> Void in
print("[log]: \(string)\n")
self.appController?.stop()
}
jsContext.setObject(unsafeBitCast(notifyEventToNative, AnyObject.self), forKeyedSubscript: "notifyEventToNative")
}
}
Just before calling "notifyEventToNative" from my TVJS, I call "navigationDocument.clear();" to clear the TVML view.
I can see my native app but I can't interact with it.
Any ideas?
Thanks.
I also had the same problem. I was opened a TVML document from the UIViewController. And I also lost the focus. So, first of all I can advice you to override var called preferredFocusedView in your ViewController. In this method you can return reference to viewAd. But the better solution would be to wrap your ViewController into the TVML-item (with the TVMLKit framework). In that case I hope that you will have no problems with focus because you will use TVML during the whole application.
I'm new in programming. I wrote a code for a body mass index app, but I can't find why I have signal SIGABRT issues.
I didn't find my response or find a good tutorial on stackoverflow.
Can you tell me what is wrong with my code please ?
Thanks
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var lblHeight: UITextField!
#IBOutlet weak var lblWeight: UITextField!
#IBOutlet weak var txtFieldResult: UILabel!
var height = 0.00
var weight = 0.00
var result = 0.00
#IBAction func btnCalcul(sender: UIButton) {
height = (lblHeight.text as NSString).doubleValue
weight = (lblWeight.text as NSString).doubleValue
if height > 0.00 {
result = weight/(height*height)
txtFieldResult.text = "\(result)"}
else {txtFieldResult.text = "Eat please"}
}
}
App delegate info
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
I have very little knowledge about Swift, xCode or Objective-C but I have read/watch a lot of tutorials and my only intention is to create a webview with notification in webkit wrapper such as this Cocoa application provided by xCode.
Currently I have my code that can pretty much run when I build it.
import Cocoa
import WebKit
class ViewController: NSViewController {
#IBOutlet weak var webView: WebView!
override func viewDidLoad() {
super.viewDidLoad()
let urlString = "https://irccloud.com"
self.webView.mainFrame.loadRequest(NSURLRequest(URL: NSURL(string: urlString)!))
}
override func webView(sender: WebView!, runJavaScriptAlertPanelWithMessage message: String!, initiatedByFrame frame: WebFrame!) {
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
}
Now, if I access irccloud url directly I'm able to receive both sound and banner notification, but I'm wondering how can I make this notification able to display like native Mac app written in Swift?
This app able to do that, but it's in Objective-C https://github.com/jnordberg/irccloudapp
I have implemented text-to-speech in my app and it works fine with the code I currently use. Basically an algo creates a text, and then if the user clicks on the UIButton the text is being spoken.
Challenge: I want to enable the same UIButton to pause the synthesizer, if the button has already been tapped (i.e. text is currently being spoken) and then resume speaking where it left off, if the button is being tapped again.
I know there are a few functions in the AVFoundation Reference but I am unable to implement them correctly.
Does anyone know how to do this in Swift?
import UIKit
import AVFoundation
#IBOutlet var generatedText: UILabel!
#IBAction func buttonSpeakClicked(sender: UIButton){
var mySpeechSynthesizer:AVSpeechSynthesizer = AVSpeechSynthesizer()
var mySpeechUtterance:AVSpeechUtterance = AVSpeechUtterance(string:generatedText.text)
mySpeechUtterance.rate = 0.075
mySpeechSynthesizer .speakUtterance(mySpeechUtterance)
}
AVSpeechSynthesizer Class Reference
Have you tried these methods?
- pauseSpeakingAtBoundary: and - continueSpeaking
And these are some properties, (paused and speaking ) that can help you determine the state of the synthesizer.
Code like this should work: mySpeechSynthesizer.pauseSpeakingAtBoundary(AVSpeechBoundary.Immediate)
In Main.storyboard, make two UIElements:
a UITextView from which the text will be read.
a UIButton to play, pause, and resume reading the text.
Create an outlet from the UITextView to the #IBOutlet and an action from the UIButton to the #IBAction in the code below. The following code is a working example, and should be your ViewController.swift:
import UIKit
import AVFoundation
class ViewController: UIViewController {
// Synth object
let synth = AVSpeechSynthesizer()
// Utterance object
var theUtterance = AVSpeechUtterance(string: "")
// Text element that the synth will read from.
#IBOutlet weak var textView: UITextView!
// Function that starts reading, pauses reading, and resumes
// reading when the UIButton is pressed.
#IBAction func textToSpeech(_ sender: UIButton) {
// The resume functionality
if (synth.isPaused) {
synth.continueSpeaking();
}
// The pause functionality
else if (synth.isSpeaking) {
synth.pauseSpeaking(at: AVSpeechBoundary.immediate)
}
// The start functionality
else if (!synth.isSpeaking) {
// Getting text to read from the UITextView (textView).
theUtterance = AVSpeechUtterance(string: textView.text)
theUtterance.voice = AVSpeechSynthesisVoice(language: "en-GB")
theUtterance.rate = 0.5
synth.speak(theUtterance)
}
}
// Standard function
override func viewDidLoad() {
super.viewDidLoad()
}
// Standard function
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Here how you can achieve this
First create a class variable of AVSpeechSynthesizer and initialize it
let synth = AVSpeechSynthesizer()
This is the button click method ( for playing the audio, or pausing it if it is already playing
#IBAction func onAVButtonClicked(_ sender: Any) {
if synth.isSpeaking {
// when synth is already speaking or is in paused state
if synth.isPaused {
synth.continueSpeaking()
}else {
synth.pauseSpeaking(at: AVSpeechBoundary.immediate)
}
}else{
// when synth is not started yet
let string = attrStr.string
let utterance = AVSpeechUtterance(string: string)
utterance.voice = AVSpeechSynthesisVoice(language: "en-US")
synth.speak(utterance)
}
}