click on a label in Swift - ios

I want to make the label that on click on it to make call to number. I know that iOS has this option, but how can I do it in Swift?
I found just how to do it in ObjC:
-(IBAction)callPhone:(id)sender {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:#"tel:2135554321"]];
}
Can anyone help me with it?

UIApplication.sharedApplication().openURL(NSURL(string: "tel://2135554321"))
example
if let CallURL:NSURL = NSURL(string:"tel://\(yourMobileNUmber)") {
let application:UIApplication = UIApplication.sharedApplication()
if (application.canOpenURL( CallURL)) {
application.openURL( CallURL);
}
else
{
// your number not valid
let tapAlert = UIAlertController(title: "Alert!!!", message: "Your mobile number is invalid", preferredStyle: UIAlertControllerStyle.Alert)
tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
self.presentViewController(tapAlert, animated: true, completion: nil)
}
}
Type-2
// add gesture to your Label
var tapGesture = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
yourLabelName.userInteractionEnabled=true
yourLabelName.addGestureRecognizer(tapGesture)
// handle the function of UILabel
func handleTap(sender:UITapGestureRecognizer){
if let CallURL:NSURL = NSURL(string:"tel://\(yourMobileNUmber)") {
let application:UIApplication = UIApplication.sharedApplication()
if (application.canOpenURL( CallURL)) {
application.openURL( CallURL);
}
else
{
// your number not valid
let tapAlert = UIAlertController(title: "Alert!!!", message: "Your mobile number is invalid", preferredStyle: UIAlertControllerStyle.Alert)
tapAlert.addAction(UIAlertAction(title: "OK", style: .Destructive, handler: nil))
self.presentViewController(tapAlert, animated: true, completion: nil)
}
}
}

Related

Check of Location permissions set

My iOS app has been rejected by Apple as the app crashes if a user selected "Dont allow" location access. And the proceeds to tap on my Map button.
How can I wrap this button in check to see if the user has given permission, And if not how can I ask for permission again?
//Map Button Action - Opens Maps - Gives choice of Google or Apple maps
#IBAction func googleMapBtn(_ sender: UIButton) {
UIDevice.current.isBatteryMonitoringEnabled = true
let state = UIDevice.current.batteryState
//If user is in Loop - Cant open maps
if state == .charging {
print("In Loop - Cant open maps")
}
//Present Map Options
else {
let alertController = UIAlertController.init(title: "Open Map", message: "", preferredStyle: .alert)
alertController.addAction(UIAlertAction.init(title: "Google Maps", style: .default, handler: { (action) in
self.googleMapsOpen()
}))
alertController.addAction(UIAlertAction.init(title: "Apple Maps", style: .default, handler: { (action) in
self.appleMapsOpen()
}))
alertController.addAction(UIAlertAction.init(title: "Back", style: .default, handler: { (action) in
self.dismiss(animated: true, completion: nil)
}))
self.present(alertController, animated: true) {
}
}
}
The code crashes whenever a user selects a map type Google/Apple and the self.googleMapsOpen() or self.appleMapsOpen() are executed. Specifically is crashed on the let scheme=
func googleMapsOpen(){
print("Google Maps Pressed")
let scheme = "comgooglemaps://?center=\(LocationManager.sharedInstance.location.coordinate.latitude),\(LocationManager.sharedInstance.location.coordinate.longitude)&zoom=15"
self.open(scheme: scheme)
}
func appleMapsOpen(){
print("Apple Maps Pressed")
let scheme = "http://maps.apple.com/?ll=\(LocationManager.sharedInstance.location.coordinate.latitude),\(LocationManager.sharedInstance.location.coordinate.longitude)&zoom=15"
self.open(scheme: scheme)
}
You can do something like this :
func checkLocationPermissionEnabled()
{
if CLLocationManager.locationServicesEnabled()
{
switch(CLLocationManager.authorizationStatus())
{
case .notDetermined, .restricted, .denied:
self.openDeviceLocationSetting()
return
case .authorizedAlways, .authorizedWhenInUse:
//do whatever you want to do with location
return
}
}
else
{
self.openDeviceLocationSetting()
return
}
}
func openDeviceLocationSetting()
{
let alertController = UIAlertController(title: "", message:"For best results, let your device turn on location using Google's location service.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
self.isAlertShowing = false
let settingsUrl = NSURL(string: UIApplicationOpenSettingsURLString)
if let url = settingsUrl {
UIApplication.shared.openURL(url as URL)
}
}
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.default) {
UIAlertAction in
}
alertController.addAction(okAction)
alertController.addAction(cancelAction)
self.present(alertController, animated: true, completion: nil)
}

Show UIAlertController every time view controller launches

Currently, the UIAlertController appears when the user taps on the HeaderButton. I am trying to make the UIAlertController automatically appear every time the view controller initially launches. Any suggestions?
// MARK: - RestaurantListTableViewHeaderDelegate
extension RestaurantListViewController: RestaurantListTableViewHeaderDelegate {
func didTapHeaderButton(_ headerView: RestaurantListTableViewHeader) {
let locationPicker = UIAlertController(title: "Select location", message: nil, preferredStyle: .actionSheet)
for location in RestaurantListViewController.locations {
locationPicker.addAction(UIAlertAction(title: location, style: .default) { [weak self] action in
guard let `self` = self else { return }
self.currentLocation = action.title
self.tableView.reloadData()
})
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
locationPicker.addAction(cancelAction)
present(locationPicker, animated: true)
}
}
I kept the extension for when the Header Button gets tapped and I added the following to viewDidLoad:
// Code for showing alert
let locationPicker = UIAlertController(title: "Select location", message: nil, preferredStyle: .actionSheet)
for location in RestaurantListViewController.locations {
locationPicker.addAction(UIAlertAction(title: location, style: .default) { [weak self] action in
guard let `self` = self else { return }
self.currentLocation = action.title
self.tableView.reloadData()
})
}
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
locationPicker.addAction(cancelAction)
present(locationPicker, animated: true)
It's not an elegant solution but it will work:
var alertAlreadyShown = false
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if !alertAlreadyShown {
alertAlreadyShown = true
/* Code for showing alert */
}
}

Change UIAlertController message or title during its presentation

Is posible change the title or message text of UIAlertController while its ViewController is presenting.
For example I present an alert when a user press a button with this message:
"Waiting for redeem code"
Then I use Alamofire to make a request and get the code, after I have it I want to change the message from alert without dissmising and presenting it again, for example the new message text is it:
"Your redeem code is : ########"
Updated
Here is my code:
#IBAction func offerAction(_ sender: UIButton) {
var code: String = "Generating códe"
let message: String = "El código para redimir esta oferta es: \(code)"
let alert = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "Accept", style: .default, handler: nil)
let redirect = UIAlertAction(title: "Website", style: .default) { (_) in
// TODO open url web
}
if offer.redeemOfferOnline == .yes {
alert.addAction(redirect)
}
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
offer.code.getRedeemCode(id: offer.id) { (success, data) in
if success {
code = data
alert.message = message
// TODO end the code of changing the message of alert
}
}
}
this is possible of course, please check the following:
class MyViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let alertController = UIAlertController(title: "My Title", message: "My Message", preferredStyle: .alert)
present(alertController, animated: true, completion: nil)
// Do your queries and get your new title and then set the new title
alertController.title = "Your new title"
}
}
It is possible to change the title and/or text AND animate the change, thusly:
[UIView transitionWithView: alertController.view
duration: 0.3
options: UIViewAnimationOptionTransitionCrossDissolve
animations: ^(void) {
alertController.message = newMessage;
}
completion: nil];
Or in Swift:
UIView.transition(with: alertController.view,
duration: 0.3,
options: .transitionCrossDissolve,
animations: { alertController.message = newMessage }
)
Just define you alertcontroller as:
var controller:UIAlertController?
Then initialize your alert controller like this:
controller = UIAlertController(title: "Title", message: "Yo", preferredStyle: .alert)
self.present(controller!, animated: true, completion: nil)
Now when you get the data from server, call this:
self.controller?.title = "New Title"
displayMyAlertMessage(userMessage: "Keshav Gera");
func displayMyAlertMessage(userMessage: String)
{
let alert = UIAlertController(title: "Success", message: userMessage, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
let imgTitle = UIImage(named:"imgTitle.png")
let imgViewTitle = UIImageView(frame: CGRect(x: 10, y: 10, width: 30, height: 30))
imgViewTitle.image = imgTitle
alert.view.addSubview(imgViewTitle)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}

How to show Actionsheet in iPad

How can I show a UIActionsheet in iPad when I'm using my current code its giving me this error:
Your application has presented a UIAlertController (<UIAlertController: 0x7f9ec624af70>) of style UIAlertControllerStyleActionSheet. The modalPresentationStyle of a UIAlertController with this style is UIModalPresentationPopover. You must provide location information for this popover through the alert controller's popoverPresentationController. You must provide either a sourceView and sourceRect or a barButtonItem. If this information is not known when you present the alert controller, you may provide it in the UIPopoverPresentationControllerDelegate method -prepareForPopoverPresentation.
which is working totally fine in an iPhone :
let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
let reminderAction = UIAlertAction(title: "Reminder", style: .Default, handler: {
(alert: UIAlertAction!) -> Void in }
optionMenu.addAction(reminderAction)
self.presentViewController(optionMenu, animated: true, completion: nil)
I came across some similar problems, the solution was this:
let optionMenu = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
optionMenu.popoverPresentationController?.sourceView = self.view
optionMenu.popoverPresentationController?.sourceRect = self.view.bounds
but it didnt worked for me maybe because my ActionSheet's Sender is on a UItableviewCell.
I tired to set AlertController's Sourceview to tableView's Cell but its not correctly placed and sometime its partially visible this is what I tried:
optionMenu.popoverPresentationController?.sourceView = currentCell.contentView
optionMenu.popoverPresentationController?.sourceRect = currentCell.contentView.bounds
Any clue how can I fix this problem?
The sample code given below works both on iPhone and iPad.
guard let viewRect = sender as? UIView else {
return
}
let cameraSettingsAlert = UIAlertController(title: NSLocalizedString("Please choose a course", comment: ""), message: NSLocalizedString("", comment: ""), preferredStyle: .ActionSheet)
cameraSettingsAlert.modalPresentationStyle = .Popover
let photoResolutionAction = UIAlertAction(title: NSLocalizedString("Photo Resolution", comment: ""), style: .Default) { action in
}
let cameraOrientationAction = UIAlertAction(title: NSLocalizedString("Camera Orientation", comment: ""), style: .Default) { action in
}
let flashModeAction = UIAlertAction(title: NSLocalizedString("Flash Mode", comment: ""), style: .Default) { action in
}
let timeStampOnPhotoAction = UIAlertAction(title: NSLocalizedString("Time Stamp on Photo", comment: ""), style: .Default) { action in
}
let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel) { action in
}
cameraSettingsAlert.addAction(cancel)
cameraSettingsAlert.addAction(cameraOrientationAction)
cameraSettingsAlert.addAction(flashModeAction)
cameraSettingsAlert.addAction(timeStampOnPhotoAction)
cameraSettingsAlert.addAction(photoResolutionAction)
if let presenter = cameraSettingsAlert.popoverPresentationController {
presenter.sourceView = viewRect;
presenter.sourceRect = viewRect.bounds;
}
presentViewController(cameraSettingsAlert, animated: true, completion: nil)
If you want to show any ActionSheet on iPad so their use popoverPresentationController to show and at iPad don't show the cancel style button of action sheet.
Use this code in Swift 3:
#IBAction func ActionSheetShow(_ sender: UIButton) {
let actionSheet = UIAlertController(title: "Choose any option", message: "choose as you like here!", preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Click1", style: .cancel, handler: {
action in
print("first button")
}))
actionSheet.addAction(UIAlertAction(title: "Click2", style: .default, handler: {
action in
print("second button")
}))
actionSheet.addAction(UIAlertAction(title: "Click3", style: .destructive, handler: {
action in
print("third button")
}))
actionSheet.popoverPresentationController?.sourceView = self.view
actionSheet.popoverPresentationController?.sourceRect = sender.frame
present(actionSheet, animated: true, completion: nil)
}
Good Luck!
Swift 4.1 Solution:-
MAK Eextension FILE UIDEviceExtension.swift and with below code :-
import Foundation
import UIKit
public extension UIDevice {
public class var isPhone: Bool {
return UIDevice.current.userInterfaceIdiom == .phone
}
public class var isPad: Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
public class var isTV: Bool {
return UIDevice.current.userInterfaceIdiom == .tv
}
public class var isCarPlay: Bool {
return UIDevice.current.userInterfaceIdiom == .carPlay
}
}
Call your action Sheet on UIViewcontroller By this Separate common method :-
import Foundation
import UIKit
class Common: NSObject{
public class func showActionSheet(vc: UIViewController,sender:UIButton? = nil) {
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (alert:UIAlertAction!) -> Void in
//self.camera()
}))
actionSheet.addAction(UIAlertAction(title: "Gallery", style: .default, handler: { (alert:UIAlertAction!) -> Void in
//self.photoLibrary()
}))
actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
//if iPhone
if UIDevice.isPhone {
vc.present(actionSheet, animated: true, completion: nil)
}
else {
//In iPad Change Rect to position Popover
if let btn = sender{
actionSheet.popoverPresentationController?.sourceRect = btn.frame
actionSheet.popoverPresentationController?.sourceView = vc.view
}
vc.present(actionSheet, animated: true, completion: nil)
}
}
}
Use it from your UIButton Click for iPhone/iPad both :-
#objc func btnPicImageTaped(btn:UIButton){
print("it will work for both iPhone /ipad")
Common.showActionSheet(vc: self,sender: btn)
}
Add Following two lines before presentViewController. (Swift 3.2)
optionMenu.popoverPresentationController?.sourceView = self.view
optionMenu.popoverPresentationController?.sourceRect = (sender as AnyObject).frame
present(optionMenu, animated: true, completion: nil)
Updated for swift 5
extension UIDevice {
class var isPhone: Bool {
return UIDevice.current.userInterfaceIdiom == .phone
}
class var isPad: Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
class var isTV: Bool {
return UIDevice.current.userInterfaceIdiom == .tv
}
class var isCarPlay: Bool {
return UIDevice.current.userInterfaceIdiom == .carPlay
}
}
You can take sourceView & sourceRect from sender:
#IBAction func btMenuPressed(_ sender: Any) {
let Sender = sender as? UIButton
let actSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
actSheet.addAction(UIAlertAction(title: "settings", style: .default) { _ in self.doSettings() })
...
...
actSheet.popoverPresentationController?.sourceView = Sender!.superview!
actSheet.popoverPresentationController?.sourceRect = Sender!.frame
resent(actSheet, animated: true)
}
Swift 5+ solution Very smooth and easy just call this function and you will easy solve your problem
let IPAD = UIDevice.current.userInterfaceIdiom == .pad
//Mark:- Choose Action Sheet Methods
func actionSheet() {
var actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertController.Style.actionSheet)
actionSheet.view.tintColor = UIColor.black
let button1 = UIAlertAction(title: "Button 1".localizableString(language: Defaults.selectedLanguageCode), style: .default, handler: {
(alert: UIAlertAction!) -> Void in
})
let button2 = UIAlertAction(title: "Button 2".localizableString(language: Defaults.selectedLanguageCode), style: .default, handler: {
(alert: UIAlertAction!) -> Void in
})
let cancelAction = UIAlertAction(title: "Cancel".localizableString(language: Defaults.selectedLanguageCode), style: .cancel, handler: {
(alert: UIAlertAction!) -> Void in
})
if IPAD {
//In iPad Change Rect to position Popover
actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertController.Style.alert)
}
actionSheet.addAction(button1)
actionSheet.addAction(button2)
actionSheet.addAction(cancelAction)
print("Action Sheet Open")
self.present(actionSheet, animated: true, completion: nil)
}

Check on UIAlertController TextField for enabling the button

I have an AlertController with a text field and two button: CANCEL and SAVE. This is the code:
#IBAction func addTherapy(sender: AnyObject)
{
let addAlertView = UIAlertController(title: "New Prescription", message: "Insert a name for this prescription", preferredStyle: UIAlertControllerStyle.Alert)
addAlertView.addAction(UIAlertAction(title: "Cancel",
style: UIAlertActionStyle.Default,
handler: nil))
addAlertView.addAction(UIAlertAction(title: "Save",
style: UIAlertActionStyle.Default,
handler: nil))
addAlertView.addTextFieldWithConfigurationHandler({textField in textField.placeholder = "Title"})
self.presentViewController(addAlertView, animated: true, completion: nil)
}
What I want to do is implement a check on the textfield for disabling the SAVE button when the textfield is empty just like Pictures Application of iOS when you want create a NewAlbum. Please someone can explain me what to do?
There is a much simpler way without using notification center, in swift:
weak var actionToEnable : UIAlertAction?
func showAlert()
{
let titleStr = "title"
let messageStr = "message"
let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.alert)
let placeholderStr = "placeholder"
alert.addTextField(configurationHandler: {(textField: UITextField) in
textField.placeholder = placeholderStr
textField.addTarget(self, action: #selector(self.textChanged(_:)), for: .editingChanged)
})
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: { (_) -> Void in
})
let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (_) -> Void in
let textfield = alert.textFields!.first!
//Do what you want with the textfield!
})
alert.addAction(cancel)
alert.addAction(action)
self.actionToEnable = action
action.isEnabled = false
self.present(alert, animated: true, completion: nil)
}
func textChanged(_ sender:UITextField) {
self.actionToEnable?.isEnabled = (sender.text! == "Validation")
}
I would first create the alertcontroller with the save action initially disabled. Then when adding the textfield inculde a Notification to observe its change in the handler and in that selector just toggle the save actions enabled property.
Here is what I am saying:
//hold this reference in your class
weak var AddAlertSaveAction: UIAlertAction?
#IBAction func addTherapy(sender : AnyObject) {
//set up the alertcontroller
let title = NSLocalizedString("New Prescription", comment: "")
let message = NSLocalizedString("Insert a name for this prescription.", comment: "")
let cancelButtonTitle = NSLocalizedString("Cancel", comment: "")
let otherButtonTitle = NSLocalizedString("Save", comment: "")
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
// Add the text field with handler
alertController.addTextFieldWithConfigurationHandler { textField in
//listen for changes
NSNotificationCenter.defaultCenter().addObserver(self, selector: "handleTextFieldTextDidChangeNotification:", name: UITextFieldTextDidChangeNotification, object: textField)
}
func removeTextFieldObserver() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UITextFieldTextDidChangeNotification, object: alertController.textFields[0])
}
// Create the actions.
let cancelAction = UIAlertAction(title: cancelButtonTitle, style: .Cancel) { action in
NSLog("Cancel Button Pressed")
removeTextFieldObserver()
}
let otherAction = UIAlertAction(title: otherButtonTitle, style: .Default) { action in
NSLog("Save Button Pressed")
removeTextFieldObserver()
}
// disable the 'save' button (otherAction) initially
otherAction.enabled = false
// save the other action to toggle the enabled/disabled state when the text changed.
AddAlertSaveAction = otherAction
// Add the actions.
alertController.addAction(cancelAction)
alertController.addAction(otherAction)
presentViewController(alertController, animated: true, completion: nil)
}
//handler
func handleTextFieldTextDidChangeNotification(notification: NSNotification) {
let textField = notification.object as UITextField
// Enforce a minimum length of >= 1 for secure text alerts.
AddAlertSaveAction!.enabled = textField.text.utf16count >= 1
}
I am doing this in another project - I got this pattern directly from apple examples. They have a very good example project outlining a few of these patterns in the UICatalog examples: https://developer.apple.com/library/content/samplecode/UICatalog/Introduction/Intro.html
Swift 3.0 Updated Solution given By #spoek
func showAlert()
{
let titleStr = "title"
let messageStr = "message"
let alert = UIAlertController(title: titleStr, message: messageStr, preferredStyle: UIAlertControllerStyle.alert)
let placeholderStr = "placeholder"
alert.addTextField(configurationHandler: {(textField: UITextField) in
textField.placeholder = placeholderStr
textField.addTarget(self, action: #selector(self.textChanged(_:)), for: .editingChanged)
})
let cancel = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel, handler: { (_) -> Void in
})
let action = UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: { (_) -> Void in
let textfield = alert.textFields!.first!
//Do what you want with the textfield!
})
alert.addAction(cancel)
alert.addAction(action)
self.actionToEnable = action
action.isEnabled = false
self.present(alert, animated: true, completion: nil)
}
func textChanged(_ sender:UITextField) {
self.actionToEnable?.isEnabled = (sender.text! == "Validation")
}
I implemented a subclass of UIAlertController for conveniently adding text fields and associated enabling and disabling of buttons. The basic logic is similar to that Sourabh Sharma but everything is encapsulated in this subclass for tidiness. This should be helpful if your project involves a lot of such alert functionalities.
public class TextEnabledAlertController: UIAlertController {
private var textFieldActions = [UITextField: ((UITextField)->Void)]()
func addTextField(configurationHandler: ((UITextField) -> Void)? = nil, textChangeAction:((UITextField)->Void)?) {
super.addTextField(configurationHandler: { (textField) in
configurationHandler?(textField)
if let textChangeAction = textChangeAction {
self.textFieldActions[textField] = textChangeAction
textField.addTarget(self, action: #selector(self.textFieldChanged), for: .editingChanged)
}
})
}
#objc private func textFieldChanged(sender: UITextField) {
if let textChangeAction = textFieldActions[sender] {
textChangeAction(sender)
}
}
}
To use it, just provide a textChangeAction block when adding the text fields:
alert.addTextField(configurationHandler: { (textField) in
textField.placeholder = "Your name"
textField.autocapitalizationType = .words
}) { (textField) in
saveAction.isEnabled = (textField.text?.characters.count ?? 0) > 0
}
For the full example, see the git page.

Resources