Want to use UIAlertController inside an Alamofire reponseJSON block - ios

The UIAlertControllers are not being executed or are not being displayed. If i solely write a print statement then there's output in the console but now the print statements are also not being executed(if i write them along with the UIAlertControllers like in the code i wrote below).
Alamofire.request(some_url, method: .post, parameters: data, encoding: URLEncoding.default, headers: nil).responseJSON{
response in
let json = JSON(response.result.value)
print(json)
self.eventid = json[0]["EventRegID"].stringValue
if !json[0]["AuthKeyError"].exists(){
if !json[0]["ExceptionOccured"].exists(){
if !json[0]["RegistrationFailed"].exists() {
if !json[0]["EventInHold"].exists() {
if json[0]["RegistrationSuccess"].exists() {
let alertController = UIAlertController(title: "", message: json[0]["RegistrationSuccess"].stringValue, preferredStyle: .alert)
let no1Action = UIAlertAction(title: "OK", style: .default) { (action) -> Void in
print("The user has registered successfully")
}
alertController.addAction(no1Action)
}
else{
}
}
else {
let alertController = UIAlertController(title: "", message: "Event is on hold.", preferredStyle: .alert)
let no2Action = UIAlertAction(title: "OK", style: .default) { (action) -> Void in
print("The event is on hold.")
}
let yes2Action = UIAlertAction(title: "GO", style: .default) { (action) -> Void in
self.performSegue(withIdentifier: "bullshit", sender: self)
}
alertController.addAction(no2Action)
alertController.addAction(yes2Action)
}
}
else {
print("Registration failed due to connection issues. Please login.")
let alertController = UIAlertController(title: "", message: "Registration failed", preferredStyle: .alert)
let no3Action = UIAlertAction(title: "OK", style: .default) { (action) -> Void in
print("The registration failed")
}
alertController.addAction(no3Action)
}
}
else {
print("There's some problem with the database")
let alertController = UIAlertController(title: "", message: "Some problem with the server", preferredStyle: .alert)
let no4Action = UIAlertAction(title: "OK", style: .default) { (action) -> Void in
print("The user has registered successfully")
}
alertController.addAction(no4Action)
}
}
else {
print("AuthKeyError")
let alertController = UIAlertController(title: "", message: "Auth key error", preferredStyle: .alert)
let no5Action = UIAlertAction(title: "OK", style: .default) { (action) -> Void in
print("AAUTH KEY ERROR")
}
alertController.addAction(no5Action)
}
}
}
else {
print("not ok")
}
}

you need to present the alertcontroller after addAction
presentViewController(alertController, animated: true, completion: nil)
maybe you have to present it in a new operation
OperationQueue.main.addOperation {
presentViewController(alertController, animated: true, completion: nil)
}

Related

How to put a success or error alert inside an options alert?

I have a problem trying to put an alert message after completing the action. The application crashes.
#IBAction func deleteAccountAction(_ sender: Any) {
let userID = prefs.value(forKey: "userId") as! String
print("user id: \(userID)")
let alert = UIAlertController(title: "Delete account", message: "Are you sure you want to delete your account?, This action cannot be reversed.", preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) { (action) in
// ...
}
let okayAction = UIAlertAction(title: "OK", style: .default) { (action) in
RestAPIManager.sharedInstance.deleteAccount(userID: userID){
(json, error) in
if(json != JSON.null){
print(json)
if(json["success"] == true){
//here i want succes alert
}else{
self.errorAlert()
}
}else{
}
}
}
alert.addAction(okayAction)
alert.addAction(cancelAction)
self.present(alert, animated: true)
}
func errorAlert(){
var dialogMessage = UIAlertController(title: "Error", message: "Error", preferredStyle: .alert)
self.present(dialogMessage, animated: true, completion: nil)
}
I tried to put an alert message after the action but I can't.
is solved needs to be async.
DispatchQueue.main.async {
self.errorAlert()
}

iOS App Crashes on every device except devices connected with Xcode

My app crashes and quit when user try to register a new account but that occurs on any device except devices deployed the app with Xcode.
All the devices are registered in the developer account and running iOS 11.4.1
Here is the register button function:
#IBAction func regButton(_ sender: Any) {
usernameText = usernameTextField.text
mobileText = mobileTextField.text
emailText = emailTextField.text
passwordText = passwordTextField.text
fieldText = categoryTextField.text
print(usernameText ?? "damn")
print(mobileText ?? "damn")
print(emailText ?? "damn")
print(passwordText ?? "damn")
print(fieldText ?? "damn")
if(type=="Seeker")
{
let url1 = "http://app.alosboiya.com.sa/hourjob.asmx/insert_jobseeker?name="+usernameText!+"&phone="+mobileText!
let url2 = "&email="+emailText!+"&password="+passwordText!+"&workex="+"companyDescText!"
let url3 = "&category="+fieldText!+"&image="+"downloadURLGlobal!"
let url4 = "&unpaidhour="+"string"+"&hourpaidlast30="+"string"+"&totalhourworked="+"string"+"&balance="+"string"+"&username="+usernameText!
stringURL = url1 + url2 + url3 + url4
}else
{
let url1 = "http://app.alosboiya.com.sa/hourjob.asmx/insert_company?name="+usernameText!+"&field="+fieldText!
let url2 = "&phone="+mobileText!+"&email="+emailText!+"&password="+passwordText!+"&workex="+"companyDescText!"+"&crcopy="+"downloadURLGlobal!"+"&logo="+"string"+"&username="+usernameText!
stringURL = url1 + url2
}
if Reachability.isConnectedToNetwork()
{
if(checkbox.on==true)
{
let url = URL(string: stringURL!)
Alamofire.request(url!).responseString {
(response) in
let result = response.result.value
do {
if(result=="True")
{
let alert = UIAlertController(title: "Registration Successfully", message: "Registration Done Successfully Congratulations",
preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style:
UIAlertActionStyle.default, handler: self.doSomething))
self.present(alert, animated: true, completion: nil)
}else
{
let alert = UIAlertController(title: "Registration Failed", message: "Registration Failed Please Try Again", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}
}
}else
{
let alert = UIAlertController(title: "License Agreement", message: "Check to Agree Licence Agreement", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}else
{
let alert = UIAlertController(title: "No Network Connection", message: "Connection Error Please Try Again", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (action) in
alert.dismiss(animated: true, completion: nil)
}))
self.present(alert, animated: true, completion: nil)
}
}
If a user will tap the button but one or both text fields are empty then your app will crash due to forced unwraping (! mark) which you use in your code.
Example: if mobileText field will be empty then the your app will crash:
let url1 = "http://app.alosboiya.com.sa/hourjob.asmx/insert_jobseeker?name="+usernameText!+"&phone="+mobileText!
the solution is to use guard statement
guard let usernameText = usernameTextField.text,
mobileText = mobileTextField.text,
emailText = emailTextField.text,
passwordText = passwordTextField.text,
fieldText = categoryTextField.text else {
return
}

Checking the value in textfield before alert controller hides - iOS swift

What I am trying to do is that I am taking user's contact number (mobile number) if it is correct then it should continue the signup otherwise the alert controller should not hide and show some error
let alertController = UIAlertController(title: "Phone Number", message: "Please enter your number", preferredStyle: .alert)
alertController.addTextField {
(textField) -> Void in
textField.tag = 128
textField.delegate = self
textField.placeholder = "923xxxxxxxxx"
}
alertController.addAction(UIAlertAction(title: "Continue", style: .default, handler: {
alert -> Void in
let textField = alertController.textFields![0] as UITextField
if (textField.text?.count)! == 12 && ((textField.text?.substring(to: 3))!) == "923" {
//my code
}
else {
//should show/keep alert controler
}
}))
self.present(alertController, animated: true, completion: nil)
Try out this,
let alertController = UIAlertController(title: "Phone Number", message: "Please enter your number", preferredStyle: .alert)
alertController.addTextField {
(textField) -> Void in
textField.tag = 128
textField.delegate = self
textField.placeholder = "923xxxxxxxxx"
}
alertController.addAction(UIAlertAction(title: "Continue", style: .default, handler: {
alert -> Void in
let textField = alertController.textFields![0] as UITextField
if (textField.text?.count)! == 12 && ((textField.text?.substring(to: 3))!) == "923"
{
//my code
}
else
{
//alert with error
let alertControllerError = UIAlertController(title: "error", message: "error here", preferredStyle: .alert)
alertControllerError.addAction(UIAlertAction(title: "ok", style: .default, handler: { alert -> Void in
}))
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) {
self.present(alertControllerError, animated: true, completion: nil)
}
}
}))
self.present(alertController, animated: true, completion: nil)
You could disable the button (UIAlertAction) by default. Then listen to text changes in your UITextField and update the button accordingly:
var autoEnableAlertAction: UIAlertAction?
func presentAlertController() {
// alert controller
let ac = UIAlertController(title: "Registration", message: "Please enter your phone number.", preferredStyle: .Alert)
// alert action - disabled by default
let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
okAction.enabled = false
ac.addAction(okAction)
// store a reference to the alert action to enable / disable it later
autoEnableAlertAction = okAction
ac.addTextFieldWithConfigurationHandler { tf in
// listen for changes in the textfield
tf.addTarget(self, action: #selector(self.checkTextFieldText(_:)), forControlEvents: .EditingChanged)
}
presentViewController(ac, animated: true, completion: nil)
}
#objc func checkTextFieldText(textField: UITextField) {
autoEnableAlertAction?.enabled = textField.text?.characters.count >= 5
}
Sorry for my answer being a Swift 2 version... :)
func presentAlertController()
{
let alertController = UIAlertController(title: "Phone Number", message: "Please enter your number", preferredStyle: .alert)
alertController.addTextField {
(textField) -> Void in
textField.tag = 128
textField.placeholder = "923xxxxxxxxx"
}
alertController.addAction(UIAlertAction(title: "Continue", style: .default, handler: {
alert -> Void in
let textField = alertController.textFields![0] as UITextField
if (textField.text?.count)! == 12 && textField.text?.prefix(3) == "923"
{
print("sucess")
}
else
{
print("Incorrect Number")
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(2)) {
self.presentAlertController(parameters: parameters)
}
}
}))
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler:{
alert -> Void in
}))
self.present(alertController, animated: true, completion: nil)
}

UIAlertController from extension

I have code to test the insertion of only digits.
How can I make an alert with a message if I insert letters?
String+onlyNumbers.swift
extension String {
func onlyNumbers() ->String{
do{
let regex = try NSRegularExpression(pattern: "([//.,\\d])*", options:[.dotMatchesLineSeparators])
var result : String = ""
for resultMatch in regex.matches(in: self, options: NSRegularExpression.MatchingOptions.init(rawValue: 0), range: NSMakeRange(0, NSString(string: self).length)) {
result += NSString(string: self).substring(with: resultMatch.range)
}
return result
}
catch
{
}
return ""
}
}
ViewControler.swift
let saveAction = UIAlertAction(title: NSLocalizedString("Past",comment: ""), style: .default, handler: {
(alert: UIAlertAction!) -> Void in
self.displayResultLabel.text = UIPasteboard.general.string?.onlyNumbers()
print("Pasted")
})
"""""
let saveAction = UIAlertAction(title: NSLocalizedString("Past",comment: ""), style: .default, handler: {
(alert: UIAlertAction!) -> Void in
if UIPasteboard.general.string?.onlyNumbers() == "" {
let alertController = UIAlertController(title: "Calc Pro", message: UIPasteboard.general.string, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alertController, animated: false, completion: nil)
} else {
self.displayResultLabel.text = UIPasteboard.general.string
}
print("Pasted")
})
You create an alert by instantiating a UIAlertController. You can use the output of your onlyNumbers function as the message of the alert controller.
Then you need to add UIAlertAction(s) to it and finally call self.present to display the alert controller from a UIViewController subclass.
if UIPasteboard.general.string?.onlyNumbers() == "" {
let alertController = UIAlertController(title: "Calc Pro", message: UIPasteboard.general.string?, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alertController, animated: false, completion: nil)
}

UIAlertController title and message not appearing

I am using this code:
let alertController = UIAlertController(title: "Default AlertController", message: "A standard alert", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action:UIAlertAction!) in
print("you have pressed the Cancel button");
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
print("you have pressed OK button");
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion:nil)
And this is what it looks like:
Here is is what the code around the presentation looks like. I am checking the auth status of CloudKit and then presenting an alert if there is an error:
dispatch_async(dispatch_get_main_queue(), {
self.activityIndicator.stopAnimating()
guard let user = user where succeeded && error == nil else {
if let error = error {
switch error {
default:
let alertController = UIAlertController(title: "Default AlertController", message: "A standard alert", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action:UIAlertAction!) in
print("you have pressed the Cancel button");
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
print("you have pressed OK button");
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion:nil)
}
}
return
}
})

Resources