Set a second reminder when create reminder button pressed in Swift 3 - ios

I've created an appointment reminder app for customers but a few have said they would like the app to give them an earlier notification say one day in advance (24 hours) as well as at the time of the appointment, but I'm unsure how I can edit my code to do this.
Here is my working code that shows the appointment at the chosen time on the date picker:
import UIKit
import EventKit
class RemindersViewController: UIViewController {
#IBOutlet weak var reminderText: UITextField!
#IBOutlet weak var myDatePicker: UIDatePicker!
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
let appDelegate = UIApplication.shared.delegate
as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func setReminder(_ sender: AnyObject) {
if reminderText.text == "" {
// Create the alert controller
let alertController = UIAlertController(title: "Information Needed", message: "Please type in your treatment and select the correct date and time you wish to be reminded about before pressing the Create Appointment Reminder button.", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "Got It", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
// Add the actions
alertController.addAction(okAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
} else {
activityIndicator.startAnimating()
let eventStore = EKEventStore()
eventStore.requestAccess(
to: EKEntityType.reminder, completion: {(granted, error) in
if !granted {
print("Access to store not granted")
print(error!.localizedDescription)
} else {
print("Access granted")
self.createReminder(in: eventStore)
}
})
}
self.reminderText.resignFirstResponder()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func createReminder(in eventStore: EKEventStore) {
let reminder = EKReminder(eventStore: eventStore)
reminder.title = reminderText.text! + " " + "(Pose Beauty Salon)"
reminder.calendar =
eventStore.defaultCalendarForNewReminders()
let date = myDatePicker.date
let alarm = EKAlarm(absoluteDate: date)
reminder.addAlarm(alarm)
do {
try eventStore.save(reminder,
commit: true)
} catch let error {
print("Reminder failed with error \(error.localizedDescription)")
}
// Create the alert controller
let alertController = UIAlertController(title: "Reminder Created Successfully", message: "Your \(reminderText.text!) appointment reminder at Pose Beauty Salon has been successfully created in your iPhone Reminders app. Thank You!", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
self.reminderText.text = ""
self.activityIndicator.stopAnimating()
}
// Add the actions
alertController.addAction(okAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
reminderText.endEditing(true)
}
}
I've changed my code as follows but I only get the reminder saved once:
func createReminder(in eventStore: EKEventStore) {
let reminder = EKReminder(eventStore: eventStore)
let secondReminder = EKReminder(eventStore: eventStore)
reminder.title = reminderText.text! + " " + "(Pose Beauty Salon)"
reminder.calendar =
eventStore.defaultCalendarForNewReminders()
secondReminder.title = reminderText.text! + " Tomorrow " + "(Pose Beauty Salon)"
secondReminder.calendar =
eventStore.defaultCalendarForNewReminders()
// let date = myDatePicker.date
let actualDate = myDatePicker.date
let earlyReminderDate = actualDate.addingTimeInterval(-3600*24)
//let alarm = EKAlarm(absoluteDate: date)
let alarm = EKAlarm(absoluteDate: actualDate)
let secondAlarm = EKAlarm(absoluteDate: earlyReminderDate)
reminder.addAlarm(alarm)
secondReminder.addAlarm(secondAlarm)

It seems that eventStore.defaultCalendarForNewReminders() doesn't allow for multiple alarms.
You can achieve this behaviour if you save the reminder to the calendar app instead.
I made some changes to your code to do this, hopefully this is useful:
Updated the access request
let eventStore = EKEventStore()
eventStore.requestAccess(
to: EKEntityType.event, completion: {(granted, error) in
if !granted {
print("Access to store not granted")
print(error!.localizedDescription)
} else {
print("Access granted")
self.createReminder(in: eventStore)
}
})
Create an EKEvent instead of EKReminder and open the EKEventEditViewController
func createReminder(in eventStore: EKEventStore) {
let reminder = EKEvent(eventStore: eventStore)
reminder.title = reminderText.text! + " " + "(Pose Beauty Salon)"
reminder.calendar =
eventStore.defaultCalendarForNewEvents
let date = myDatePicker.date
let alarm = EKAlarm(absoluteDate: date)
reminder.addAlarm(alarm)
let earlierDate = date.addingTimeInterval(-3600*24)
let earlierAlarm = EKAlarm(absoluteDate: earlierDate)
reminder.addAlarm(earlierAlarm)
reminder.startDate = date
reminder.endDate = date.addingTimeInterval(3600)
do {
try eventStore.save(reminder, span: .thisEvent, commit: true)
} catch let error {
print("Reminder failed with error \(error.localizedDescription)")
return
}
// Create the alert controller
let alertController = UIAlertController(title: "Reminder Created Successfully", message: "Your \(reminderText.text!) appointment reminder at Pose Beauty Salon has been successfully created in your iPhone Reminders app. Thank You!", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
self.reminderText.text = ""
self.activityIndicator.stopAnimating()
}
// Add the actions
alertController.addAction(okAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
}
Added delegate method from EKEventEditViewDelegate
func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
switch action
{
case .saved:
let alertController = UIAlertController(title: "Reminder Created Successfully", message: "Your \(reminderText.text!) appointment reminder at Pose Beauty Salon has been successfully created in your iPhone Reminders app. Thank You!", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
self.reminderText.text = ""
self.activityIndicator.stopAnimating()
}
// Add the actions
alertController.addAction(okAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
default:
self.dismiss(animated: true, completion: nil)
}
}

You could create two separate reminders with all same data but with different dates like this:
let actualDate = myDatePicker.date
let earlyReminderDate = actualDate.addingTimeInterval(-3600*24)

Related

Validating user swift 4, login page

I need to my button proceedToAppFeatures to run the code and display an alert of success or failure login(just a single user, for now)
I have tried self.showAlert and self.present
Code:
import UIKit
import FLAnimatedImage
import ImageIO
import UserNotifications//import this to use user notifications
import Firebase
class ViewController: UIViewController, UITextFieldDelegate{
#IBOutlet weak var background: FLAnimatedImageView!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var lblValidationTxt: UILabel!
#IBOutlet weak var lblValidationMessage: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
background.loadGif(name: "neon lights")
passwordTextField.isSecureTextEntry = true// the password will no be visible
emailTextField.delegate = self
passwordTextField.delegate = self
let Tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(DismissKeyboard))//here i have used the function to didmiss the keyboard
view.addGestureRecognizer(Tap)
let center = UNUserNotificationCenter.current()
//this initialize the permission that will appear on user screen
center.requestAuthorization(options: [.alert, .sound, .badge]) {
(granted,error) in
//enable or disable features based on the authorization
}
// emailTextField.text = ""
// passwordTextField.text = ""//on view did load to store text field property
}
#objc func DismissKeyboard() {//function that implements the type outside the screen
view.endEditing(true)
}
#IBAction func sigInButton(_ sender: UIButton) {
performSegue(withIdentifier: "userData", sender: true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == emailTextField {
textField.resignFirstResponder()
}else{
passwordTextField.becomeFirstResponder()//just to decide which of the buttons will respond after a tab is pressed
passwordTextField.resignFirstResponder()
}
return true
}
func showAlert(title: String, message: String){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: {(action) in alert.dismiss(animated: true, completion: nil)}))
self.present(alert, animated: true, completion: nil)
}
func isValidEmail(testStr:String) -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+#[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}"
let emailTest = NSPredicate(format:"SELF MATCHES %#", emailRegEx)
return emailTest.evaluate(with: testStr)
}
#IBAction func proceedToAppFeatures(_ sender: Any) {
let email = isValidEmail(testStr: emailTextField.text!)
if email == false{
self.showAlert(title: "ERROR", message: "This is not a valid e-mail. Please try again")
emailTextField.text = ""
}else{
self.showAlert(title: "Success", message: "Yousucessifully loged in")
//performSegue(withIdentifier: "formPage", sender: true)
}
let myEmail: String!
myEmail = emailTextField.text!
let myPassword: String!
myPassword = passwordTextField.text!
if(myEmail == "leandroaaramos" && myPassword == "123456"){
//performSegue(withIdentifier: "homeSegue", sender: nil)
//code for the truth
print("You are success")
}else if (myEmail.isEmpty && myPassword.isEmpty){
//here i put the alert message
let alert = UIAlertController(title: "Wow", message: "Hold on fill the gaps", preferredStyle: UIAlertController.Style.alert)
//add an action to the alert
alert.addAction(UIAlertAction(title: "Close", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
self.showAlert(title: "Empty field", message: "Try again")
}else {
//here i put the alert message
let alert = UIAlertController(title: "Ops", message: "Your account is not here", preferredStyle: UIAlertController.Style.alert)
//add an action to the alert
alert.addAction(UIAlertAction(title: "Try Again", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
self.showAlert(title: "Sorry", message: "Can't find you.")
}
}
}
I want go to my loginViewController, if the user leandroaaramos and password 123456 was typed.

Core data doesn't seem to be saved

I am trying to create an app that requires the user to successfully enter a pin before being allowed onto the rest of the app.
I did some searching around and found a basic existing coredata example app that works here.
I went into the xcdatamodel and deleted their attributes and replaced with "pin" which is a String. Here is a screenshot of the xcdatamodel.
Then I modified the ViewController so that the createData UIbutton opens a alertController that prompts the user to enter a new pin twice, checks they are the same, and if they are it creates a coredata entry with that pin.
Here is the relevant code of the ViewController:
import UIKit
import CoreData
class ViewController: UIViewController {
var firstPinNumber:String = ""
var secondPinNumber:String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func createData(_ sender: Any) {
let enterPinAlertController = UIAlertController(title: "Enter New PIN", message: "", preferredStyle: .alert)
enterPinAlertController.addTextField{ (textField1:UITextField)->Void in
textField1.placeholder = "Enter PIN"
textField1.isSecureTextEntry = true
}
enterPinAlertController.addTextField{ (textField2:UITextField)->Void in
textField2.placeholder = "Re-Enter PIN"
textField2.isSecureTextEntry = true
}
let okAction = UIAlertAction(title: "OK", style: .cancel) {(action) in
if let textFields = enterPinAlertController.textFields {
let theTextFields = textFields as [UITextField]
self.firstPinNumber = theTextFields[0].text!
self.secondPinNumber = theTextFields[1].text!
if self.firstPinNumber != self.secondPinNumber {
print ("PINs dont match!")
let pinsDontMatchAlertController = UIAlertController(title: "PINs don't match!", message: "Try again", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel) {(action) in
}
pinsDontMatchAlertController.addAction(okAction)
self.present(pinsDontMatchAlertController, animated: true, completion: nil)
}
}
}
enterPinAlertController.addAction(okAction)
self.present(enterPinAlertController, animated: true, completion: nil)
createPIN(pinNum: secondPinNumber)
}
func createPIN(pinNum: String){
//As we know that container is set up in the AppDelegates so we need to refer that container.
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
//We need to create a context from this container
let managedContext = appDelegate.persistentContainer.viewContext
//Now let’s create an entity and new user records.
let userEntity = NSEntityDescription.entity(forEntityName: "User", in: managedContext)!
let user = NSManagedObject(entity: userEntity, insertInto: managedContext)
user.setValue(pinNum, forKeyPath: "pin")
print(user.value(forKey: "pin") as Any)
//Now we have set the pin. The next step is to save it inside the Core Data
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
#IBAction func retrieveData(_ sender: Any) {
let storedPin = retrievePIN()
print(storedPin)
}
func retrievePIN()->String {
var storedPin:String = ""
//As we know that container is set up in the AppDelegates so we need to refer that container.
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return "" }
//We need to create a context from this container
let managedContext = appDelegate.persistentContainer.viewContext
//Prepare the request of type NSFetchRequest for the entity
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
fetchRequest.fetchLimit = 1
// fetchRequest.predicate = NSPredicate(format: "username = %#", "Ankur")
// fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "email", ascending: false)]
//
do {
let result = try managedContext.fetch(fetchRequest)
for data in result as! [NSManagedObject] {
if data.value(forKey: "pin") != nil {
storedPin = data.value(forKey: "pin") as! String
print(storedPin)
} else {
print ("Found nil")
}
}
} catch {
print("Failed")
}
return storedPin
}
Using breakpoints I have ascertained that it enters the createPin() function, but it seems to enter that function BEFORE it presents the enterPinAlertController to enter the new pin, even though createPin() is called AFTER the enterPinAlertController is presented.
Also if I use the retrieveData UIButton it prints out "Found nil"
So if what I'm thinking is correct, its creating a coredata entry with an empty string, or nothing at all?
How can I fix this so that it creates a coredata entry with the string the user enters as the new pin, and also retrieves it later?
Your call to createPin needs to be inside the action handler for okAction. As you have it now, secondPinNumber will be called before the alert has been shown, so it will be empty or nil, depending on how you initialise it.
IBAction func createData(_ sender: Any) {
let enterPinAlertController = UIAlertController(title: "Enter New PIN", message: "", preferredStyle: .alert)
enterPinAlertController.addTextField{ (textField1:UITextField)->Void in
textField1.placeholder = "Enter PIN"
textField1.isSecureTextEntry = true
}
enterPinAlertController.addTextField{ (textField2:UITextField)->Void in
textField2.placeholder = "Re-Enter PIN"
textField2.isSecureTextEntry = true
}
let okAction = UIAlertAction(title: "OK", style: .cancel) {(action) in
if let textFields = enterPinAlertController.textFields,
let firstPinNumber = textFields[0].text,
let secondPinNumber = textFields[1].text,
firstPinNumber == secondPinNumber {
createPIN(pinNum: secondPinNumber)
} else {
print ("PINs dont match!")
let pinsDontMatchAlertController = UIAlertController(title: "PINs don't match!", message: "Try again", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel)
pinsDontMatchAlertController.addAction(okAction)
self.present(pinsDontMatchAlertController, animated: true, completion: nil)
}
}
}
enterPinAlertController.addAction(okAction)
self.present(enterPinAlertController, animated: true, completion: nil)
}

name textfield made mandatory then UIAlert stopped working

I added a line of code so that name text-field is mandatory when registering an account with firebase but when I did that the UIAlert broke. It stopped showing up when I added that line of code. The code I added is highlighted with a >. What is the best way to fix the problem? Either recode the mandatory name text-field or recode the UIAlert. Which is the simplest way?
#IBAction func registerTapped(_ sender: Any) {
let namec = nameTextField.text
if let email = emailTextField.text, let pass = passwordTextField.text, let name = (namec?.capitalized.isEmpty)! ? nil:namec?.capitalized {
FIRAuth.auth()?.createUser(withEmail: email, password: pass, completion: { (user, error) in
if user != nil {
//user found
let interval = NSDate().timeIntervalSince1970
let date = Date(timeIntervalSince1970: interval)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd/MM/yyyy/HH/mm/SS"
// you can change the date format to whatever you wants
let dateString = dateFormatter.string(from: date)
print(dateString)
self.refD?.child("Users").child((user?.uid)!).setValue(["Email": email, "Name": name, "User Created": dateString])
print("User Created And Added To Database", email, name, dateString)
self.performSegue(withIdentifier: "registertologin", sender: self)
}
else {
print(error!)
let alert = UIAlertController(title: "Error Creating Account ", message: "\(error!.localizedDescription)", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
})
}
}
}
i think you have to add alert code in the main queue block because your code is inside a completion handler block
DispatchQueue.main.async {
print(error!)
let alert = UIAlertController(title: "Error Creating Account ", message: "\(error!.localizedDescription)", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
Try this!

Sending data (label and date picker) from my app to the Reminders app

I've created an appointment reminder section in my app but it seems the first use of the app doesn't get stored? When I click the create reminder button I get my popup alert saying it was successfully created followed by the would like to access your reminders popup. Because of this people's first appointments aren't being stored, and I can't figure out what I have done wrong?
Here is my code:
import UIKit
import EventKit
class FirstViewController: UIViewController {
#IBOutlet weak var reminderText: UITextField!
#IBOutlet weak var myDatePicker: UIDatePicker!
let appDelegate = UIApplication.shared.delegate
as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func setReminder(_ sender: AnyObject) {
if reminderText.text == "" {
// Create the alert controller
let alertController = UIAlertController(title: "Information Needed", message: "Please type in your treatment and select the correct date and time you wish to be reminded about before pressing the Create Appointment Reminder button.", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "Got It", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
// Add the actions
alertController.addAction(okAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
} else {
if appDelegate.eventStore == nil {
appDelegate.eventStore = EKEventStore()
appDelegate.eventStore?.requestAccess(
to: EKEntityType.reminder, completion: {(granted, error) in
if !granted {
print("Access to store not granted")
print(error!.localizedDescription)
} else {
print("Access granted")
}
})
}
if (appDelegate.eventStore != nil) {
self.createReminder()
}
}
self.reminderText.resignFirstResponder()
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
func createReminder() {
let reminder = EKReminder(eventStore: appDelegate.eventStore!)
reminder.title = reminderText.text! + " " + "(Pose Beauty Salon)"
reminder.calendar =
appDelegate.eventStore!.defaultCalendarForNewReminders()
let date = myDatePicker.date
let alarm = EKAlarm(absoluteDate: date)
reminder.addAlarm(alarm)
do {
try appDelegate.eventStore?.save(reminder,
commit: true)
} catch let error {
print("Reminder failed with error \(error.localizedDescription)")
}
// Create the alert controller
let alertController = UIAlertController(title: "Reminder Created Successfully", message: "Your \(reminderText.text!) appointment reminder at Pose Beauty Salon has been successfully created in your iPhone Reminders app. Thank You! ", preferredStyle: .alert)
// Create the actions
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
UIAlertAction in
NSLog("OK Pressed")
}
// Add the actions
alertController.addAction(okAction)
// Present the controller
self.present(alertController, animated: true, completion: nil)
reminderText.text = ""
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
reminderText.endEditing(true)
}
}
Your logic is much more complicated than it needs to be. You can take advantage of the fact that when you request access to the event store after access has already been granted (or denied) then those permissions are used without prompting the user.
It is also poor form to initialise a property of the AppDelegate from some other class. You probably don't even need the EventStore on the AppDelegate - you can just create an instance when you need it.
You can use something like:
} else {
let eventStore = EKEventStore()
eventStore.requestAccess(
to: EKEntityType.reminder, completion: {(granted, error) in
if !granted {
print("Access to store not granted")
print(error!.localizedDescription)
} else {
print("Access granted")
self.createReminder(in: eventStore)
}
})
}
func createReminder(in eventStore: EKEventStore) {
....
}

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