Text Input Controller WatchKit - swift

I am trying to use presentTextInputControllerWithSuggestions in a WatchKit app.
I am not sure where I am going wrong.
presentTextInputControllerWithSuggestions(["Hello", "Hey"], completion: {
(myString) -> Void in
println(myString)
})

From the iOS 8.2 Release Notes:
WatchKit
Known Issues
The presentTextInputControllerWithSuggestions:completion: method of
WKInterfaceController is not currently supported in iOS Simulator.

You can try by tapping on a suggestion. It should do exactly the same as dictating.
Beware, the completion returns an array and not a string.
You should do it like that
self.presentTextInputControllerWithSuggestions(["Suggestion 1", "Suggestion 2"] allowedInputMode: .Plain, completion: { (selectedAnswers) -> Void in
if reply && reply.count > 0 {
if let spokenReply = selectedAnswers[0] as? String {
println("\(spokenReply)")
}
}
})

From Apple Dev Forums
Its the same a pressing microphone on the iPhone keyboard and dictating.
The Audio goes off to apple and returns and hopefully the text you spoke is returned as a String.

Related

Xcode warning: 'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a relevant window scene instead

when updating my App's Deployment target to 15.0, i receive this warning:
'windows' was deprecated in iOS 15.0: Use UIWindowScene.windows on a
relevant window scene instead
I have tried to look on the net what could be done to remediate this, but couldn't find much info on this. Hope you could share some advice.
The line of code i am using where this alert occurred is:
let window = UIApplication.shared.windows[0]
followed by in my ViewDidLoad():
DispatchQueue.main.async { [weak self] in
if defaults.bool(forKey: "darkModeBoolSwitch") == true {
self?.window.overrideUserInterfaceStyle = .dark
} else if defaults.bool(forKey: "darkModeBoolSwitch") == false {
self?.window.overrideUserInterfaceStyle = .light
}
An alternative to #DuncanC's solution that may also work for you: UIApplication has a connectedScenes property, which lists all of the currently-active scenes doing work in your application (for most applications, this is just the one main scene).
Of those scenes, you can filter for scenes which are UIWindowScenes (ignoring scenes which are not currently active and in the foreground), and of those, find the first scene which has a window which is key:
extension UIApplication {
static var firstKeyWindowForConnectedScenes: UIWindow? {
UIApplication.shared
// Of all connected scenes...
.connectedScenes.lazy
// ... grab all foreground active window scenes ...
.compactMap { $0.activationState == .foregroundActive ? ($0 as? UIWindowScene) : nil }
// ... finding the first one which has a key window ...
.first(where: { $0.keyWindow != nil })?
// ... and return that window.
.keyWindow
}
}
I hesitate to call this extension something like UIApplication.keyWindow because the reason for the deprecation of these APIs is because of the generalization to multi-scene applications, each of which may have its own key window... But this should work.
If you still need to support iOS 14, which does not have UIWindowScene.keyWindow, you can replace the firstWhere(...)?.keyWindow with: flatMap(\.windows).first(where: \.isKeyWindow).
I am out-of-date with Apple's recent changes to implement scenes.
I did a little digging, and found a protocol UIWindowSceneDelegate
It looks like you are supposed to add an "Application Scene Manifest" to your app's info.plist file that tells the system the class that serves as the app's window scene delegate.
Then in that class you want to implement the method scene(_:willConnectTo:options:). When that method is called you sould try to cast the UIScene that's passed to you to to a UIWindowScene, and if that cast succeeds, you can ask the window scene for it's window and save it to an instance property.
That should allow you to save a pointer to your app's window and use it when needed.

Cannot find "UIScreen" in scope [duplicate]

This question already has an answer here:
Adjust screen brightness in Mac OS X app
(1 answer)
Closed last year.
I've just approached Swift, for building a quick utility app for my MacBook.
I have written the following code, but it gives me the error "Cannot find 'UIScreen' in scope".
class AppDelegate: NSObject,NSApplicationDelegate{
//...
func applicationDidFinishLaunching(_ notification: Notification) {
Timer.scheduledTimer(withTimeInterval: 10, repeats: true) { timer in
UIScreen.mainScreen().brightness = CGFloat(0.0) //<- error here
}
}
//...
}
Initially I thought I've missed an import, but I cannot find what to import (UIKit, is only for iOS).
Thank you for any help
Anything beginning with "UI" is an iOS class. Those classes are not available from a macOS app.
The equivalent class for macOS is probably NSScreen, although I don't think it has an exposed brightness property like the one you are trying to set.
Edit:
It looks like it is possible to set the screen brightness in MacOS, but you have to use much lower-level code. Check out this link.
The relevant code from that link is the following, which uses IOKit:
func setBrightnessLevel(level: Float) {
var iterator: io_iterator_t = 0
if IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching("IODisplayConnect"), &iterator) == kIOReturnSuccess {
var service: io_object_t = 1
while service != 0 {
service = IOIteratorNext(iterator)
IODisplaySetFloatParameter(service, 0, kIODisplayBrightnessKey, level)
IOObjectRelease(service)
}
}
}

Is there away to completely override a line of code based on a condition set?

I creating this app for my church and one feature is a prayer wall. I am using firebase as my database integrated with google sign in. When a user post a prayer request it displays their display names amongst other things. I implemented a switch and some line of code to change the display name to anonymous if the switch is on. That works however it adds anonymous after the display name. Please see the examples below.
I am really new to swift and I am self taught this is my first app, any help would be greatly appreciated.
#IBAction func didPostPrayerRequest(_ sender: Any) {
var userInfo = Auth.auth().currentUser?.displayName
if privacyFilter.isOn {
userInfo?.append("anonymous")
}
let prayerPosted:[String: Any] = ["praydate": [".sv":"timestamp"], "prayer": prayerPostText.text!,"username":userInfo!]
prayerRef?.child("Prayers").childByAutoId().setValue(prayerPosted)
print("Any")
//Dismiss popover
presentingViewController?.dismiss(animated: true, completion: nil)
}
Screenshot
Simply overwrite the value using userInfo = "anonymous" instead of appending to it.

NotificationCenter handler updates variable but UILabel stays the same

Using Xcode 10.1 running the app on mini iPad OS 12.1.1
I am posting a notification to NotificationCenter and the handler function updates UILabel setupProgress to show the progress of a data import.
This used to work fine but has recently stopped working, very possibly as a result of something I have done, but I can't think what.
PM in the code is a function which prints to the console - and it tells me that self.setupProgress.text is, in fact, set correctly and changes as expected as the data loads, however the corresponding UILabel does not update.
The initial UILabel text is set like this
if !self.update_type.isEmpty && self.update_type == "setup_import" {
self.setupProgress.text = "I've told the server that this is a clean install"
}
and that works fine - but then, as the import progresses, in the handler function (below) I get no updates until
import_progress == "And now the end is upon us ..."
at which point the UILabel updates correctly and everything carries on as expected.
func handleImportNotification(_ notification:Notification) {
self.setupProgress.text = import_progress
// should show something like
// `Importing F4RES : 0 of : 1395`
// `Importing F4RES : 500 of : 1395`
// etc...
PM(#line, function: #function, str1: self.setupProgress.text)
// prints the correct updates to the console
if import_progress == "And now the end is upon us ..." {
self.makeShopOptions()
self.loadingImage.stopAnimating()
self.performSegue(withIdentifier: "setup_to_splash", sender: self)
}
}
The app continues to work just fine - just without the expected UILabel updates in between.
Thanks in advance for any ideas.
You are posting a notification to the Notification Center. Would you mind showing how and when?
Assuming you're using NotificationCenter.default.post notificationName: method, the handler should take an argument of type Notification. Otherwise it won't respond to notification updates.
The handler function should look like:
func handleImportNotification(notification: Notification) { ... }
And the observer:
var observer: NSObjectProtocol?
func someFunction() {
observer = NotificationCenter.default.addObserver(forName: object: queue: using: { (Notification) in
//Update UILabel or call the associated function
}))
}
Try this.

Yowza restored status bar too many times

As I call function OpenGC then the leaderboard appears fine, but when I close the Game Center everything is fine, but then I get the following errors in debug:
2018-04-03 01:12:10.143194+0300 app.name[356:38176] [Error] yowza! restored status bar too many times!
2018-04-03 01:12:10.161688+0300 app.name[356:38176] [Error] Extension request cancelled with error: Error Domain=NSExtensionErrorDomain Code=-2 "Extension cancelled by host." UserInfo={NSLocalizedDescription=Extension cancelled by host.}
The code i am using is here:
#IBAction func OpenGC(_ sender: Any) {
let VC = self
let GCVC = GKGameCenterViewController()
GCVC.gameCenterDelegate = self
GCVC.viewState = .leaderboards
GCVC.leaderboardIdentifier = "my.leaderboard"
VC.present(GCVC, animated: true, completion: nil)
}
func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) {
gameCenterViewController.dismiss(animated: true, completion: nil)
I have found same issue but no solution in:
Unity Forum
Really appreciate if anyone has ideas!
Thanks
We've encountered this error as well on our tvOS build (iOS is working fine) using Xcode 10.2.1. Upon further investigation done by a colleague, seems that other tvOS games found on the tvOS AppStore are experiencing the same behavior.
I've filed a bug with Apple, but at the time of writing it seems that nobody managed to fix this so you're better off just submiting it like this until Apple provides a fix for this issue.