How to use a UIAlertController in MVVM? - ios

I have a VC with code to show an alert:
func showMessage() {
let alertView = UIAlertController(title: "TEST",
message: self.loginViewModel.errorText,
preferredStyle: .alert)
alertView.addAction(UIAlertAction(title: "Ok", style: .destructive, handler: nil))
present(alertView, animated: true, completion: nil)
}
and I have this login logic in my viewModel which needs to trigger this function:
func submitLoginRequest(userLogin: String, loginPassword: String, loginSecret: String, deviceToken: String) {
let userLogin = UserServices.init()
manager.userServicesApiRequest(url: Endpoints.login, request: userLogin) { (data, error) in
if let data = data {
let status = data["status"].stringValue
if status == "success" {
guard let userObject = UserProfileModel.init(data) else { return }
let encodedUserObject: Data = NSKeyedArchiver.archivedData(withRootObject: userObject)
UserDefaults.standard.set(encodedUserObject, forKey: "userProfile")
print("Login Succeeded") self.coordinatorDelegate?.loginViewModelDidLogin(viewModel: self)
} else {
self.errorText = data["reason"].stringValue
// here is where the controller needs calling!
}
}
I wanted to know how i should have them interact correctly to trigger the VC when the VM case is hit?

Related

How can I add another button that'll also scan the qrcode but post to a different URL

Now, I have a button that will trigger the camera function to scan the
qrcode and then will post the result to the PHP script.
How can I add another button that'll also scan the qrcode but post to a
different URL.
I have tried to add another button but it kept posting to the same URL
class ViewController: UIViewController,
QRCodeReaderViewControllerDelegate,CLLocationManagerDelegate{
//scan
#IBOutlet weak var previewView: QRCodeReaderView! {
didSet {
previewView.setupComponents(showCancelButton: false, showSwitchCameraButton: false, showTorchButton: false, showOverlayView: true, reader: reader)
}
}
}
}
//QR code reader
lazy var reader: QRCodeReader = QRCodeReader()
lazy var readerVC: QRCodeReaderViewController = {
let builder = QRCodeReaderViewControllerBuilder {
$0.reader = QRCodeReader(metadataObjectTypes: [.qr], captureDevicePosition: .back)
$0.showTorchButton = true
$0.reader.stopScanningWhenCodeIsFound = false
}
return QRCodeReaderViewController(builder: builder)
}()
// MARK: - Actions
private func checkScanPermissions() -> Bool {
do {
return try QRCodeReader.supportsMetadataObjectTypes()
} catch let error as NSError {
let alert: UIAlertController
switch error.code {
case -11852:
alert = UIAlertController(title: "Error", message: "This app is not authorized to use Back Camera.", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Setting", style: .default, handler: { (_) in
DispatchQueue.main.async {
if let settingsURL = URL(string: UIApplicationOpenSettingsURLString) {
UIApplication.shared.openURL(settingsURL)
}
}
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
default:
alert = UIAlertController(title: "Error", message: "Reader not supported by the current device", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
}
present(alert, animated: true, completion: nil)
return false
}
}
//scan
#IBAction func scanInModalAction(_ sender: AnyObject) {
guard checkScanPermissions() else { return }
readerVC.modalPresentationStyle = .formSheet
readerVC.delegate = self
readerVC.completionBl ock = { (result: QRCodeReaderResult?) in
if let result = result {
print("Completion with result: \(result.value) of type \(result.metadataType)")
}
}
present(readerVC, animated: true, completion: nil)
}
// MARK: - QRCodeReader Delegate Methods
func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult){
reader.stopScanning()
dismiss(animated: true) { [weak self] in
//device id
let deviceUUID: String = (UIDevice.current.identifierForVendor?.uuidString)!
//POST REQUEST start
let myUrl2 = URL(string: ((self?.myString)! + "/testing00/attendance/scan.php"));
var request = URLRequest(url:myUrl2!)
request.httpMethod = "POST"// Compose a query string
let postString = "imie=" + deviceUUID + "&qrcode=" + result.value
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(error)")
return
}
if let data = data {
let string = String(data: data, encoding: String.Encoding.utf8)
print(string) //
DispatchQueue.main.async {
self?.outlet4.text = string
}
}
}
task.resume()
}
}
func readerDidCancel(_ reader: QRCodeReaderViewController) {
reader.stopScanning()
dismiss(animated: true, completion: nil)
}
}

Display alert in current view, and as well as Redirect to another view

I want to display alert for check new version of my app from API. And from that view if userDefault data is store so base on that I want to redirect to another view. My redirection code is work perfectly but when I add alert code so redirection doesn't work. I think alert present in "self" and that time I also try to redirect from that view so it's may create problem. Here is my code..
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateUserData() //base on userDefault redirection
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
checkNewVersion() //Alert function for API calling
}
func checkNewVersion() -> Void {
//TODO: For check App new version
WebRequester.shared.getAppNewVersion { (result, error) in
if result != nil {
if result?.value(forKey: "status") as! Bool {
let strVer = (result?.object(forKey: "data") as! NSDictionary).object(forKey: "platform_version") as! String
if UserData.getAppVersion() < strVer {
let alert = UIAlertController(title: "Alert", message: "New version of App available", preferredStyle: .alert)
let ok = UIAlertAction(title: "Ok", style: .default, handler: { (action) in
})
let AppStore = UIAlertAction(title: "App Store", style: .default, handler: { (action) in
if let url = URL(string: "itms-apps://itunes.apple.com/app/id1024941703"),
UIApplication.shared.canOpenURL(url){
UIApplication.shared.openURL(url)
}
})
alert.addAction(ok)
alert.addAction(AppStore)
self.present(alert, animated: true, completion: nil)
// OperationQueue().addOperation {
// // Put queue to the main thread which will update the UI
// OperationQueue.main.addOperation({
// self.present(alert, animated: true, completion: nil)
// })
// }
}
}
else {
if (result?.object(forKey: "data") as! NSArray).object(at: 0) as? String ?? "" == "Unauthorised access." {
Model.shared.deleteAllCoreDataRecord(entity: "CartItem")
UIApplication.topViewController()?.navigationController?.popToRootViewController(animated: true)
}
let msg = result?.value(forKey: "data") as! [String]
Model.shared.showAlert(title: "Error", msg: msg[0], controller: self)
}
}
else {
Model.shared.showAlert(title: "Error", msg: error?.localizedDescription ?? "Something went wrong at add new address", controller: self)
}
}
}
func updateUserData() -> Void {
if UserData.getAppVersion() == "1.0" {
if UserData.getUserData() != nil {
//TODO: check for user Updated data
let params = ["mobile":UserData.getUserMobile()] as [String : Any]
let propic = UIImage(named: "temp")
weak var objWeek = self
Model.shared.showActivity(WithTouchEnable: false,controller: self)
WebRequester.shared.customerSignup(params: params as NSDictionary, proImg: propic!){ (result,error) -> Void in
Model.shared.HideActivity(controller: self)
if (error == nil) {
print("login result:",result ?? "")
//handle response of sign up
let statusstr = result?["status"] as! Bool
if (statusstr == false) {
//This condition for pepsi welcome offer is expire or not
let user = result!["user_info"] as! NSDictionary
self.storeUserData(user: user)
if UserData.getUserMobileNumVerify() == "No" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let registerScreen = storyboard.instantiateViewController(withIdentifier: "UserRegisterPhoneVC") as! UserRegisterPhoneVC
objWeek?.navigationController?.pushViewController(registerScreen, animated: true)
}
else {
if UserData.getPepsiOfferRedim() == "1" || UserData.getPepsiOfferRedim() == "2" {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let offerScreen = storyboard.instantiateViewController(withIdentifier: "OfferViewController") as! OfferViewController
objWeek?.navigationController?.pushViewController(offerScreen, animated: true)
}
else {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let promoScreen = storyboard.instantiateViewController(withIdentifier: "PromotionViewController") as! PromotionViewController
objWeek?.navigationController?.pushViewController(promoScreen, animated: true)
}
}
}
}
}
else {
Model.shared.showAlert(title: "Error", msg: (error?.localizedDescription)!, controller: self)
}
}
}
}
}
To achieve this , you need to click on alert OK button then only it will automatically navigate to other controller , without this not possible .
Here is code :
Alert controller block help you to achieve this :
//show an alert and navigate to previous controller
let alertController: UIAlertController = UIAlertController(title: "Password updatd", message: "your alert message", preferredStyle: .alert)
let okAction: UIAlertAction = UIAlertAction(title: "OK", style: .default) { action -> Void in
//Redirect to new viewcontroler
let newVC = self.storyboard.instantiateViewcontroller(identifier: "newvc") as? NewVC
self.navigationController?.pushViewController(newVC,animated: true)
}
alertController.addAction(okAction)
self.present(alertController, animated: true, completion: nil)
Feel free to comment. Thanks

Optimizing a CloudKit sign-in on app launch with error handling. How can I better handle the optional chaining? Swift 3.0/Xcode 8.1

Is there a cleaner, swiftier solution to handle the optional chaining happening in my code below? I'm setting up the user for CloudKit access in my custom function runCKsetup():
func runCKsetup() {
container.requestApplicationPermission(.userDiscoverability) { (status, error) in
guard error == nil else {
if let error = error as? NSError {
if let errorDictionary: AnyObject = error.userInfo as? Dictionary<String, AnyObject> as AnyObject? {
let localizedDescription = errorDictionary["NSLocalizedDescription"]! as! String!
if localizedDescription! == "This operation has been rate limited" {
// Create an alert view
let alert = UIAlertController(title: "Network Error", message: localizedDescription!, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Test for Connection", style: UIAlertActionStyle.default) { (action) in
self.runCKsetup()
})
self.present(alert, animated: true, completion: nil)
} else {
// Create an alert view
let alert = UIAlertController(title: "Sign in to iCloud", message: localizedDescription!, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default) { (action) in
})
self.present(alert, animated: true, completion: nil)
}
}
}
return
}
if status == CKApplicationPermissionStatus.granted {
self.container.fetchUserRecordID { (recordID, error) in
guard error == nil else {
self.presentMessageAlert((error?.localizedDescription)!, title: "Error", buttonTitle: "Ok")
return }
guard let recordID = recordID else { return }
self.container.discoverUserIdentity(withUserRecordID: recordID, completionHandler: { (info, fetchError) in
//do something with the users names: e.g. print("\(info?.nameComponents?.givenName) \(info?.nameComponents?.familyName)")
})
}
}
}
}

Swift iOS How to display an alert message from the handler of another alert message

I'm trying to implement a forgot password feature in my app so users can enter their email in and have it reset in the database and have the new generated password emailed to them.
I believe my code should work once I fix a few minor issues but the main hurdle I'm having is how to display an alert message from the handler of another alert message.
Any idea how to do it? Either the alert message doesn't show up at all or the first one doesn't close at all.
Here is my attempt at it:
//This function will send a password reset email
func emailPassword(alertAction: UIAlertAction!) -> Void {
let textField = reset_alert.textFields![0] as UITextField
if(!textField.text!.isEmpty){
if(textField != "mik"){
let query = PFQuery(className: "_User")
let forgotten_email = textField.text
query.whereKey("email", equalTo: forgotten_email!)
query.findObjectsInBackgroundWithBlock{
(objects: [PFObject]?, error: NSError?) -> Void in
//NO ERROR//
if(error == nil){
//email in db generate random password
let letters : NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let randomString : NSMutableString = NSMutableString(capacity: 12)
var users_name = ""
for _ in 0...10{
let length = UInt32 (letters.length)
let rand = arc4random_uniform(length)
randomString.appendFormat("%C", letters.characterAtIndex(Int(rand)))
}
//set new password for user
if let objects = objects {
for object in objects {
object["_hashed_password"] = randomString
users_name = object["name"] as! String
//send password to email
self.mailgun.sendMessageTo("\(users_name) <\(textField)>", from: "")
self.displayAlert("SUCCESS", msg: "Check your email for your new password")
self.reset_alert.dismissViewControllerAnimated(true, completion: nil)
}
}
else{
self.reset_alert.dismissViewControllerAnimated(true, completion: nil)
self.displayAlert("ERROR", msg: "Email not registered to an account")
}
}
//ERROR//
else{
self.reset_alert.dismissViewControllerAnimated(true, completion: nil)
self.displayAlert("ERROR", msg: "Email not registered to an account") }
} //end if textfield not admin email
self.presentViewController(reset_alert, animated: true, completion: nil)
}
}//end of if textfield is empty
}
Try this extension:
typealias AlertActionBlock = (UIAlertAction) -> Void
extension UIViewController {
func flash(title title:String?, message:String?, cancelTitle:String?, actions:UIAlertAction?...) {
let b = {
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
let cancelBlock:AlertActionBlock = {(action:UIAlertAction) -> Void in }
let cancelAction = UIAlertAction(title: cancelTitle, style: UIAlertActionStyle.Cancel, handler: cancelBlock)
alertController.addAction(cancelAction)
for action in actions {if let action = action {alertController.addAction(action)}}
self.presentViewController(alertController, animated: true, completion: nil)
}
if NSThread.isMainThread() {
b()
} else {
dispatch_async(dispatch_get_main_queue(), b)
}
}
}
That should let you call that function from background threads or the main thread just call that function and fill in the variables
EDIT (I didn't realize you need a textfield) so try this:
func flash(title title:String?, message:String?, textFieldConfigurator:(UITextField -> Void)? = nil, cancelTitle:String?, actions:UIAlertAction?...) {
let b = { () -> Void in
let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
if let textFieldConfigurator = textFieldConfigurator {alertController.addTextFieldWithConfigurationHandler(textFieldConfigurator)}
let cancelBlock:AlertActionBlock = {(action:UIAlertAction) -> Void in }
let cancelAction = UIAlertAction(title: cancelTitle, style: UIAlertActionStyle.Cancel, handler: cancelBlock)
alertController.addAction(cancelAction)
for action in actions {if let action = action {alertController.addAction(action)}}
self.presentViewController(alertController, animated: true, completion: nil)
}
if NSThread.isMainThread() {
b()
} else {
dispatch_async(dispatch_get_main_queue(), b)
}
}
If you need multiple text fields make it an array and iterate through it. Let me know how it goes!

UIAlertView actions not happening swift

I have a login page in my app. The user enters their username and their password. I have an API that tells me if the username and password are correct and the user's id if they are. If they are not correct it shows a UIAlertView() that asks if you would like to create an account. The view has two buttons. A "No" button which dismisses the view and a "Yes" button which is supposed to contact an API to create the user's account. I have created alert actions before but it will not work with the code I have below. If you wouldn't mind could you please take a look and help me diagnose the problem?
//
// File.swift
// Reading Logs
//
// Created by Andrew on 12/8/15.
// Copyright © 2015 Wilson Apps for Education. All rights reserved.
//
import UIKit
class UserLogin {
var loginAlert = UIAlertView()
var user: String = ""
var pass: String = ""
func checkLogin() -> Bool{
let defaults = NSUserDefaults.standardUserDefaults()
let stat = defaults.valueForKey("loggedIn")
if(String(stat!) == "0"){
return false
}else{
return true
}
}
func logout(){
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue("0", forKey: "loggedIn")
defaults.setValue("", forKey: "logKey")
defaults.setValue("0", forKey: "userKey")
}
func login(username username: String, password: String, completion: (result: String) -> Void){
self.user = username
self.pass = password
let url = "http://www.wilsonfamily5.org/rlog/checkLogin.php?u=\(username)&p=\(password)"
let nsUrl = NSURL(string:url)
let nsUrlRequest = NSURLRequest(URL: nsUrl!)
NSURLSession.sharedSession().dataTaskWithRequest(nsUrlRequest){
(data, response, error) in
guard
let data = data,
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
else { return }
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if(contents as String == "0"){
self.loginAlert = UIAlertView(title: "No Account Found", message: "We did not find an account matching that criterea. Do you want us to create you an account?", delegate:nil, cancelButtonTitle: "No")
self.loginAlert.addButtonWithTitle("Yes")
self.loginAlert.show()
}else{
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue(contents as String, forKey: "userKey")
defaults.setValue("1", forKey: "loggedIn")
completion(result: "1")
}
})
}.resume()
}
func register(username: String, password: String){
let url = "http://www.wilsonfamily5.org/rlog/newAccount.php?u=\(username)&p=\(password)"
let nsUrl = NSURL(string:url)
let nsUrlRequest = NSURLRequest(URL: nsUrl!)
NSURLSession.sharedSession().dataTaskWithRequest(nsUrlRequest){
(data, response, error) in
guard
let data = data,
let contents = NSString(data:data, encoding:NSUTF8StringEncoding)
else { return }
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setValue(contents as String, forKey: "userKey")
defaults.setValue("1", forKey: "loggedIn")
})
}.resume()
}
func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) {
print("ButtonClicked")
if(buttonIndex == 1){
print("1ButtonClicked")
register(user, password: pass)
}
}
}
Step-1
Add UIAlertViewDelegate to your class;
class UserLogin, UIAlertViewDelegate {
....
Step-2
Set delegate and implement "Yes" button loginAlert object;
self.loginAlert = UIAlertView(title: "No Account Found", message: "We did not find an account matching that criterea. Do you want us to create you an account?", delegate: self, cancelButtonTitle: "No", otherButtonTitles: "Yes")
self.loginAlert.show()
Now clickedButtonAtIndex function will be triggered.
You should use UIAlertViewController instead of UIAlertView because
UIAlertView is deprecated in iOS 9
Here is a code of UIAlertController in Swift and its pretty simple to use.The main thing is that it's Block based and No need to use any delegate
let alertController = UIAlertController(title: "Default AlertController", message: "A standard alert", preferredStyle: .Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { (action:UIAlertAction!) in
println("you have pressed the Cancel button");
}
alertController.addAction(cancelAction)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action:UIAlertAction!) in
println("you have pressed OK button");
}
alertController.addAction(OKAction)
self.presentViewController(alertController, animated: true, completion:nil)
You need to set Delegate, so you can receive alerts callbacks:
self.loginAlert = UIAlertView(title: "No Account Found", message: "We did not find an account matching that criterea. Do you want us to create you an account?", delegate:self, cancelButtonTitle: "No"

Resources