WatchKit and UIAlertView / UIAlertController popup - ios

In my WatchKit app, when the user first launches it, I would like to present to them a helpful message alert that tells them how the app works, e.g. what the buttons do, etc.
Is there something similar to UIAlertView / UIAlertController that I can call in a WatchKit app? I couldn't find an answer on this topic which may very well mean that it's not possible.

(New in watchOS 2.0)
WKAlertAction *act = [WKAlertAction actionWithTitle:#"OK" style:WKAlertActionStyleCancel handler:^(void){
NSLog(#"ALERT YES ");
}];
NSArray *testing = #[act];
[self presentAlertControllerWithTitle:#"Voila" message:#"This is Watch OS 2 !" preferredStyle:WKAlertControllerStyleAlert actions:testing];
SWIFT
func showPopup(){
let h0 = { print("ok")}
let action1 = WKAlertAction(title: "Approve", style: .default, handler:h0)
let action2 = WKAlertAction(title: "Decline", style: .destructive) {}
let action3 = WKAlertAction(title: "Cancel", style: .cancel) {}
presentAlert(withTitle: "Voila", message: "", preferredStyle: .actionSheet, actions: [action1,action2,action3])
}

i will add the swift4 result that work for me while using
WKAlertAction
watchOS 4.0
Swift 4
let action1 = WKAlertAction.init(title: "Cancel", style:.cancel) {
print("cancel action")
}
let action2 = WKAlertAction.init(title: "default", style:.default) {
print("default action")
}
let action3 = WKAlertAction.init(title: "destructive", style:.destructive) {
print("destructive action")
}
presentAlert(withTitle: "Alert Title", message: "message is here", preferredStyle:.actionSheet, actions: [action1,action2,action3])

Yes, after upgrading to watchOS 2, you can present an alert view using presentAlertController of WKInterfaceController.
See the official documentation here.

let h0 = { print("h0 action")}
let h1 = { print("h1 action")}
let action1 = WKAlertAction(title: "h0 action", style: .default, handler:h0)
let action2 = WKAlertAction(title: "h1 action", style: .default, handler:h0)
self.presentAlert(withTitle: "Title", message: "a message", preferredStyle: .actionSheet, actions: [action1, action2])
Code in Swift 3

There is no such class for alerts. However you can modally present "WKInterfaceController" with the information in "WKInterfaceLabel" and one "WKInterfaceButton".

Sadly, you can not do this. But you can of course have a modal page-based hierarchy with screenshots of how the app is working if it is the first time that the app is launched. I am doing so in my app! :)

If I could make one more suggestion: Create a separate group for your "alert" in your initial interface controller and show/hide it as needed.

Related

iOS - how to add action in new line in UIAlertConroller swift

I need to add action in new line just like: alertActionsWithNewLines
I'm trying this code:
let uncheckInAlert = UIAlertController(title: "Are you sure you want to uncheck-in?", message: "", preferredStyle: .alert)
uncheckInAlert.setTitleImage(UIImage(named: "fail_Icon"))
uncheckInAlert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (action) -> Void in
self.userUncheckIn()
}))
uncheckInAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
self.present(uncheckInAlert, animated: true, completion: nil)
But as result I have something like: alertActionsInOneLine.
If action title is large then action automatically carried over on new line. With small action title, actions is grouped in one line. Is there any a ways to do this?
There is no flag you can set in order to change how Apple lays out its alert buttons. The UIAlertController with style alert will, however, change it's button layout automatically to vertical when it cannot properly fit the entire string of the button's text in a horizontal layout. So if your button's text is long enough, it will change the layout.
Though this is a solution to your question, I don't recommend adding arbitrary spaces or unnecessarily long strings to the button's text just so Apple will layout the buttons vertically in a production app. It's misusing the standard components and could easily start breaking down once strings become localized to other languages. In order to naturally achieve the desired behavior I would suggest creating your own, custom view to display buttons vertically.
Changing these lines from
uncheckInAlert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
To
uncheckInAlert.addAction(UIAlertAction(title: "Cancel", style: .default, handler: nil))
let uncheckInAlert = UIAlertController(title: "Are you sure you want to uncheck-in?", message: "", preferredStyle: .alert)
To
let uncheckInAlert = UIAlertController(title: "Are you sure you want to uncheck-in?", message: "", preferredStyle: .actionSheet)
This will show cancel option grouped with other options.
Try change style form .alert to .actionSheet
Like in this code
let uncheckInAlert = UIAlertController(title: "Are you sure you want to uncheck-in?", message: "", preferredStyle: .actionSheet)

How do I create a loop checking app connectivity

I'm trying to create a loop on my app to check Connectivity. So, when the app loads for the first time, the user must be connected to the internet, otherwise he cannot proceed on using the app.
However, I'm trying to create a function that while the user has no internet, the UIAlerView persists on the screen until find an internet connection, then it should be dismissed and another method be lunched. What would be the best way for me to do that?
let alert = UIAlertController(title: "Primeiro Uso", message: "Voce precisa estar conectado na internet", preferredStyle: UIAlertControllerStyle.alert)
// add the actions (buttons)
alert.addAction(UIAlertAction(title: "Estou Conectado", style: .default, handler: { action in
if Connectivity.isConnectedToInternet != true {
//How do I create a loop here until find a connection?
//I'd like to persist the UIAlerView until find a connection
}
//Once the user is connected, this code below should be
//lunched
getApiData { (cerveja) in
arrCerveja = cerveja
//Backup
do{
let data = try JSONEncoder().encode(arrCerveja)
UserDefaults.standard.set(data, forKey: "backupSaved")
//
self.tableView.reloadData()
}catch{print(error)
}
}}))
alert.addAction(UIAlertAction(title: "Cancelar", style: UIAlertActionStyle.cancel, handler: nil))
// show the alert
self.present(alert, animated: true, completion: nil)
}
you can use this answer
https://stackoverflow.com/a/3597085/2621857
in the appDelegate level of you application.
i think creating loop for checking internet, somehow will pressure the processor to memory leak so i suggest not using a kind of loop to check the internet.
i hope this will work for you .

Exit application using a UIAlertController

If a user opens up the application without an internet connection, a window pops up that says a connection is required, and there is an ok button. I want to the ok button to exit the application. Here is what I have:
if !isConnectedToNetwork(){
let alert = UIAlertController(title: "No Internet", message: "You need an internet connection to use this app", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
I am going to use this to exit the app:
UIControl().sendAction(Selector("suspend"), to: UIApplication.sharedApplication(), forEvent: nil)
I just don't know how to connect it to the OK button above.
Don't. Apple will reject this (if they see it).
Simply inform the user and add a 'retry' button. The retry button should obviously check the connection again.
To actually answer the question, you have currently set the handler: nil on the button action, instead you can actually set a handler and use it to call whatever logic you like.
You can handle when user press OK by the following code
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,
handler: { (action:UIAlertAction!) -> Void in
//after user press ok, the following code will be execute
NSLog("User pressed OK!!")
}))

Do I have to hard-code / localise myself the "OK" button when generating an alert in swift?

I have a convenience method in Swift (iOS 8+) for displaying an error message. So far it looks like this:
// Supplied with a category code and an error code, generates an error dialogue box.
// Codes rather than strings because this needs to be localisable.
func showErrorDialogue(categoryCode: String, _ errorCode: String) -> () {
// Fetch the actual strings from the localisation database.
let localisedCategory = NSLocalizedString(categoryCode, comment: categoryCode)
let localisedError = NSLocalizedString(errorCode, comment: errorCode)
// Create an alert box
let alertController = UIAlertController(
title: localisedCategory,
message: localisedError,
preferredStyle: .Alert
)
alertController.addAction(
UIAlertAction(
title: "OK", // FIXME: why isn't this localised?
style: .Default,
handler: { (action) in return }
)
)
self.presentViewController(alertController, animated: true) { return }
}
It seems odd that I can't just say "I'm only adding one button to this alert box, so please assume it's going to be the locale-default OK button". The best solution I've found so far with limited Googling appears to be Steal them from the System and hope which is more than a little dodgy.
As far as I know, there are no better ways to do this than stealing it from the system like you found.
Though it's not the hardest thing to localize, I agree it would be great if Apple made that automatic in a future version of the OS.

UIAlertView And UIAlertController

I am using SWIFT in xcode 6 to develope my application AND needs to support the APP for iphone 4 and later versions... So have selected the 'Deploment Target' as 7.1. In simple words needs to support iOS7, iOS8 AND iOS9...
When using Alert View I came across in many places discussing now we have to use newly introduced 'UIAlertController' rather than the old 'UIAlertView'...
By reading got to know UIAlertView is deprecated from ios 8.
But in my case as I have to support for ios 7.1 AND I can NOT only use 'UIAlertController'.
I started using as the following way as many tutorials explains...
if (objc_getClass("UIAlertController") != nil)
{
// Use UIAlertController
}
else
{
// Use UIAlertView
}
But in this way got to write the same code twice and really annoyiong... Either I have to create a custom Alertview combining both or needs to continue coding like this....
but just to test I've used only UIAlertView (ignoring UIAlertController) and the app runs fine even in ios 8 simulators... But the document says UIAlertView is deprecated from iOS 8.0...
So my question is, Like to hear what the best practice to continue my app with these API changes... Is it alright if I ignore 'UIAlertController' and work with old 'UIAlertView' until stop support for iOS7 one day... Will that effect in to my app in any way bad? Thanks
I've written a wrapper around these two classes which uses appropriate classes according to iOS version.
find it here
https://github.com/amosavian/ExtDownloader/blob/master/Utility%2BUI.swift
to show a simple alert use this:
Utility.UI.alertShow("message", withTitle: "title", viewController: self);
to show an action view: use this code:
let buttons = [Utility.UI.ActionButton(title: "Say Hello", buttonType: .Default, buttonHandler: { () -> Void in
print("Hello")
})]
Utility.UI.askAction("message", withTitle: "title", viewController: self, anchor: Utility.UI.AnchorView.BarButtonItem(button: uibarbuttontapped), buttons: buttons)
In case you are presenting action in iPhone, it will add a cancel button automatically. But you can have custom cancel button by defining a button with type of ".Cancel"
If you want show a modal alert view, use this code:
let cancelBtn = Utility.UI.AlertButton(title: "Cancel", buttonType: .Cancel, buttonHandler: nil)
let okBtn = Utility.UI.AlertButton(title: "OK", buttonType: .Default, buttonHandler: { (textInputs) -> Void in
print("OK button pressed")
})
Utility.UI.askAlert("message", withTitle: "title", viewController: self, buttons: [cancelBtn, okBtn], textFields: nil)
As you can see, the text fields is set to nil above. You can set it if you want ask something from user, like this:
let cancelBtn = Utility.UI.AlertButton(title: "Cancel", buttonType: .Cancel, buttonHandler: nil)
let okBtn = Utility.UI.AlertButton(title: "OK", buttonType: .Default, buttonHandler: { (textInputs) -> Void in
print("You entered" + textInputs[0])
}
})
let textFields = [Utility.UI.AlertTextField(placeHolder: "enter secret text here", defaultValue: "", textInputTraits: TextInputTraits.secretInput())]
Utility.UI.askAlert("Enter password", withTitle: "title", viewController: self, buttons: [cancelBtn, okBtn], textFields: textFields)
You can customize almost everything. e.g by defining custom textInputTrait you can customize text inputs easily. also you have not to deal with delegates, instead simple closures are there. Please read code to find out more.

Resources