unwindSegue could not pass data (Swift - Xcode) - ios

I'm using UserDefaults to store and retrieve my data but I have no idea why when I perform an unwind segue, my userdefaults data could not be passed over to the next view controller but if i do a normal push segue, my userdefaults data could be seen in the next viewcontroller.
P.S: ONLY self.performSegue(withIdentifier: "unwindSegue", sender: nil) is the unwindSegue.
FirstViewController
#IBAction func Button1(_ sender: Any) {
var i: Int = 0
let randomNumber = arc4random_uniform(3) + 1
i = Int(randomNumber)
let alert = AlertController(title: "Congratualations", message: "You earned \(i) tokens!", preferredStyle: .alert)
alert.setTitleImage(UIImage(named: "token"))
// Add actions
alert.addAction(UIAlertAction(title: "Let's See!", style: UIAlertActionStyle.default, handler: { (action) in
var returnValue: Int = UserDefaults.standard.integer(forKey: "tokens")
returnValue = returnValue + i;
UserDefaults.standard.set(returnValue, forKey:"tokens")
self.performSegue(withIdentifier: "unwindSegue", sender: nil)
}))
if (returnValue != 30){
alert.addAction(UIAlertAction(title: "Continue Playing", style: UIAlertActionStyle.default, handler: { (action) in
var returnValue: Int = UserDefaults.standard.integer(forKey: "tokens")
returnValue = returnValue + i;
UserDefaults.standard.set(returnValue, forKey:"tokens")
self.performSegue(withIdentifier: "continue", sender: self)
}))
}
self.present(alert, animated: true, completion: nil)
}
SecondViewController
import UIKit
class TokenController: UIViewController {
#IBOutlet var tokens: UILabel!
#IBOutlet var minus1: UIButton!
#IBOutlet var minus2: UIButton!
var returnValue: Int = UserDefaults.standard.integer(forKey: "tokens")
override func viewDidLoad() {
super.viewDidLoad()
tokens.text = "x\(returnValue)"
}
#IBAction func unwindSegue(_ sender: UIStoryboardSegue) {
}

Because when you do a Push of a new ViewController, this is loaded into memory and it's method "ViewDidLoad" is called.
When you do an unwind segue , the previous ViewController is already in memory, so the viewDidLoad and all the initialization are not called and the labels and all the graphics are not updated.
This is not a problem, because you can access all the data you needed in the unwindSegue implementation through the variable sender. See this example:
 
func unwindToViewController(segue: UIStoryboardSegue) {
        let vc_source = segue.source as! SecondViewController
        self.myLabel.text! = vc_sorgente.myTextField.text!      
}

#Kinja Please refer this url to use unwind segue
Click here:- Perform action when segue is closed

Related

Login page doesn't work fully it works when segue connected but doesn't check if user is registered or not

Login page doesn't really check for if user is stored in core data and will just go ahead with the segue. It should login only if user is registered in core data else will input error and to go register but register seems to work correctly tho I followed some guides online
I have attached the code please check and give me some suggestion to achieve my task
LoginVC
import UIKit
import CoreData
class LoginVC: UIViewController {
#IBOutlet weak var username: UITextField!
#IBOutlet weak var password: UITextField!
var credits = 200.0
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view
fetchData()
}
#IBAction func login(_ sender: Any) {
for acc in userList {
if acc.username == username.text && acc.password == password.text {
currentUser = username.text!
try! context.save()
//performSegue(withIdentifier: "DisplayShop1", sender: nil)
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let next = storyBoard.instantiateViewController(identifier: "DisplayShop1") as! ListingShopVC
next.modalPresentationStyle = .fullScreen
self.present(next, animated: true, completion: nil)
}
else if username.text != acc.username || password.text != acc.password || password.text == "" || username.text == "" {
let alert = UIAlertController(title: "Alert", message: "Please enter the correct credentials", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "hellothere" {
let ve = segue.destination as! ListingShopVC
ve.creditsss = credits
}
}
func fetchData(){
userList = try! context.fetch(User.fetchRequest())
}
}
RegisterVC
import UIKit
import CoreData
class RegisterVC: UIViewController {
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var userList: String = ""
#IBOutlet weak var username: UITextField!
#IBOutlet weak var cpassword: UITextField!
#IBOutlet weak var password: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
#IBAction func register(_ sender: Any) {
if username.text != ""{
if password.text != "" {
if password.text == cpassword.text {
let newu = User(context: context)
newu.username = username.text
newu.password = password.text
newu.credit = 200.0
try! context.save()
self.navigationController?.popViewController(animated: true)
}
else {
let alert = UIAlertController(title: "Alert", message: "Please enter values correctly", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Dismiss", style: .default, handler: nil))
present(alert, animated: true, completion: nil)*/
}
}
}
}

UIAlertAction actionsheet fetch data to childVC

I have a parentVC that allows user to add by using actionsheet's choices
Expected Result :
when actionsheet presented, user choose the choices and the actionsheet will perform segue to childVC and childVC's label.text will become the chosen choice
My issue is I print out self.textInAS is exactly what the action.title, however, when segue performed, textFromAS become nil, so after some research I guess I lack of closure that required, however I am still new in Swift and I not sure how to properly perform a closure. Please provide example with code to help.
Many Thanks!!
/* parentVC */
var textInAS : String?
#IBAction func addBtnPressed(_ sender: UIBarButtonItem) {
let alert = UIAlertController(title: "Alert Title", message: "alert msg", preferredStyle: .actionSheet)
let actionA = UIAlertAction(title: "Choices A", style: .default) { (action) in
let chosenTitle = action.title
self.textInAS = choosenTitle
self.performSegue(withIdentifier: "goChildVC", sender: self)
}
let actionB = UIAlertAction(title: "Choices B", style: .default) { (action) in
let chosenTitle = action.title
self.textInAS = choosenTitle
self.performSegue(withIdentifier: "goChildVC", sender: self)
}
alert.addAction(actionA)
alert.addAction(actionB)
present(alert, animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.identifier == "goChildVC") {
let destinationVC = segue.destination as! ChildTableViewController
destinationVC.textFromAS = self.textInAS
}
}
}
}
/* ChildVC */
#IBOutlet weak var label: UILabel!
var textFromAS: String?
override func viewDidLoad() {
super.viewDidLoad()
label.text = textFromAS
}

Why is my string becoming nil when used as the title of an action sheet?

In an app I am currently writing, I have a string named 'User' which stores the user's name for a game. The value of the string, when printed anywhere else in the Swift file, prints the value that I have set, as an optional.
If I try to use this string as the title of an action sheet action, the string is automatically set to nil, which I can see as both the title of the action and which is printed when I ask it to print(user).
If anyone could shed some light as to why this is happening, or how to prevent it, that would be great. I have also posted my Swift file below, thanks.
import UIKit
class MainViewController: UIViewController {
#IBOutlet weak var segmentedControl: UISegmentedControl!
#IBOutlet weak var firstView: UIView!
#IBOutlet weak var secondView: UIView!
var user:String!
var playerTwo:String!
var playerThree:String!
var playerFour:String!
var playerFive:String!
var playerSix:String!
var userCards = [String]()
override func viewDidLoad() {
super.viewDidLoad()
firstView?.isHidden = false
secondView?.isHidden = true
}
#IBAction func valueDidChange(_ sender: UISegmentedControl) {
switch segmentedControl.selectedSegmentIndex {
case 0:
firstView.isHidden = false
secondView.isHidden = true
case 1:
firstView.isHidden = true
secondView.isHidden = false
default:
break;
}
}
#IBAction func confirm(_ sender: UIButton) {
let alertController = UIAlertController(title: "Action Sheet", message: "What would you like to do?", preferredStyle: .actionSheet)
let userButton = UIAlertAction(title: user /* Here I have tried with putting both 'user', and "\(user)"*/, style: .default, handler: { (action) -> Void in
print("User button tapped")
})
let deleteButton = UIAlertAction(title: "Delete button test", style: .destructive, handler: { (action) -> Void in
print("Delete button tapped")
})
let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in
print("Cancel button tapped")
})
alertController.addAction(userButton)
alertController.addAction(deleteButton)
alertController.addAction(cancelButton)
self.present(alertController, animated: true, completion: nil)
}
}
The value is passed into the above file directly from this code in another file:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showMainController" {
let VC = segue.destination as! MainViewController
VC.user = self.user
if playerTwo != nil {
VC.playerTwo = self.playerTwo
}
if playerThree != nil {
VC.playerThree = self.playerThree
}
if playerFour != nil {
VC.playerFour = self.playerFour
}
if playerFive != nil {
VC.playerFive = self.playerFive
}
if playerSix != nil {
VC.playerSix = self.playerSix
}
}
}
The value is, however, passed through several view controllers, and is initially set here:
if (meTextField.text?.isEmpty)! == false {
let p1 = meTextField.text!
initialPlayersDict["player1"] = "\(p1)"
if errLabelNotBlank {
errorLabel.text = ""
errLabelNotBlank = false
}
}

Swift 3 - Thread 1: Signal SIGABRT

I am attempting to change views in the simulator via a button click but keep getting the error:
Thread 1: signal SIGABRT
I am aware that this usually occurs when there is a disconnect with outlets or actions but I have checked and they all seem to be linked.
AppDelegate.swift
import UIKit
import Parse
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
// Parse configuration in Heroku
let configuration = ParseClientConfiguration {
// accessing Heroku App via ID and Keys
$0.applicationId = "truegramIDDB91"
$0.clientKey = "truegramKeyDB91"
$0.server = "http://truegram.herokuapp.com/parse"
}
// call login function
login()
Parse.initialize(with: configuration)
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
func login() {
// remember user's login
let username : String? = UserDefaults.standard.string(forKey: "username")
// if logged in
if username != nil {
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let myTabBar = storyboard.instantiateViewController(withIdentifier: "tabBar") as! UITabBarController
window?.rootViewController = myTabBar
}
}
}
SignInVC.swift
import UIKit
import Parse
class signInVC: UIViewController {
// textfields
#IBOutlet weak var usernameTxt: UITextField!
#IBOutlet weak var passwordTxt: UITextField!
#IBOutlet weak var label: UILabel!
// sign in button view
#IBOutlet weak var signinBtnBlock: UIView!
// buttons
#IBOutlet weak var signInBtn: UIButton!
#IBOutlet weak var signUpBtn: UIButton!
#IBOutlet weak var forgotPasswordBtn: UIButton!
// default function
override func viewDidLoad() {
super.viewDidLoad()
// font of label (Clubbr)
label.font = UIFont(name: "gillsans-light", size: 22)
}
// clicked sign in button
#IBAction func signInBtnClick(sender: AnyObject) {
print("sign in pressed")
// hide keyboard
self.view.endEditing(true)
// if text fields are empty
if usernameTxt.text!.isEmpty || passwordTxt.text!.isEmpty {
// show alert message
let alert = UIAlertController(title: "Please", message: "fill in fields", preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
// login functions
PFUser.logInWithUsername(inBackground: usernameTxt.text!, password: passwordTxt.text!) { (user: PFUser?, error: Error?) -> Void in
if error == nil {
// remember user or save in app memory (did the user log in or not)
UserDefaults.standard.set(user!.username, forKey: "username")
UserDefaults.standard.synchronize()
// Call login function from AppDelegate.swift class
let appDelegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.login()
} else {
// show alert message
let alert = UIAlertController(title: "Error", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
SignUpVc.swift
import UIKit
import Parse
class signUpVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// profile image
#IBOutlet weak var avaImg: UIImageView!
// textfields
#IBOutlet weak var firstnameTxt: UITextField!
#IBOutlet weak var lastnameTxt: UITextField!
#IBOutlet weak var emailTxt: UITextField!
#IBOutlet weak var passwordTxt: UITextField!
#IBOutlet weak var confirmTxt: UITextField!
// buttons
#IBOutlet weak var loginBtn: UIButton!
#IBOutlet weak var signupBtn: UIButton!
#IBOutlet weak var businessSignupBtn: UIButton!
// scroll view
#IBOutlet weak var scrollView: UIScrollView!
// resets scroll view to default size
var scrollViewHeight : CGFloat = 0
// keyboard frame size
var keyboard = CGRect()
// default func
override func viewDidLoad() {
super.viewDidLoad()
// check notifications if keyboard is shown or not
NotificationCenter.default.addObserver(self, selector: Selector(("showKeyboard:")), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: Selector(("hideKeyboard:")), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
// declare hide keyboard tap
let hideTap = UITapGestureRecognizer(target: self, action: Selector(("hideKeyboardTap:")))
hideTap.numberOfTapsRequired = 1
self.view.isUserInteractionEnabled = true
self.view.addGestureRecognizer(hideTap)
// profile image circle shape and custom border colour
avaImg.layer.borderWidth = 2
avaImg.layer.borderColor = UIColor.init(red: 90/255, green: 187/255, blue: 181/255, alpha: 1).cgColor
avaImg.layer.cornerRadius = avaImg.frame.height/2
avaImg.clipsToBounds = true
// declare select image tap
let avaTap = UITapGestureRecognizer(target: self, action: Selector(("loadImg:")))
avaTap.numberOfTapsRequired = 1
avaImg.isUserInteractionEnabled = true
avaImg.addGestureRecognizer(avaTap)
}
// call picker to select image
func loadImg(recognizer: UITapGestureRecognizer) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}
// connect selected image to our image view
private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
avaImg.image = info[UIImagePickerControllerEditedImage] as? UIImage
self.dismiss(animated: true, completion: nil)
}
// hide keyboard if tapped
func hideKeyboardTap(recognizer: UITapGestureRecognizer) {
self.view.endEditing(true)
}
// show keyboard
func showKeyboard(notification: NSNotification) {
// define keyboard sizes
keyboard = ((notification.userInfo?[UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue)!
//move up UI
UIView.animate(withDuration: 0.4) { () -> Void in
self.scrollView.frame.size.height = self.scrollViewHeight - self.keyboard.height
}
}
// hide keyboard
func hideKeyboard(notification: NSNotification) {
//move down UI
UIView.animate(withDuration: 0.4) { () -> Void in
self.scrollView.frame.size.height = self.view.frame.height
}
}
// clicked sign up
#IBAction func signupBtnClick(sender: AnyObject) {
print("sign up pressed")
// dismiss keyboard
self.view.endEditing(true)
// if fields are empty
if (emailTxt.text!.isEmpty || passwordTxt.text!.isEmpty || confirmTxt.text!.isEmpty || firstnameTxt.text!.isEmpty || lastnameTxt.text!.isEmpty) {
// alert pop up message
let alert = UIAlertController(title: "Please", message: "fill all fields", preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
// if incorrect password
if passwordTxt.text != confirmTxt.text {
// alert pop up message
let alert = UIAlertController(title: "Attention", message: "incorrect password", preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
// send data to related columns in server
let user = PFUser()
user.username = emailTxt.text?.lowercased()
user.email = emailTxt.text?.lowercased()
user.password = passwordTxt.text
user["firstname"] = firstnameTxt.text?.lowercased()
user["lastname"] = lastnameTxt.text?.lowercased()
// convert our image for sending to server
let avaData = UIImageJPEGRepresentation(avaImg.image!, 0.5)
let avaFile = PFFile(name: "ava.jpg", data: avaData!)
user["ava"] = avaFile
// save data in server
user.signUpInBackground { (success: Bool, error: Error?) -> Void in
if success {
print("registered")
// remember logged user
UserDefaults.standard.set(user.username, forKey: "username")
UserDefaults.standard.synchronize()
// calls login func from AppDelegate.swift class
let appDelegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.login()
} else {
// show alert message
let alert = UIAlertController(title: "Error", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
}
}
// clicked return to log in
#IBAction func loginBtnClick(sender: AnyObject) {
self.dismiss(animated: true, completion: nil)
// dismiss keyboard
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
ResetPasswordVC.swift
import UIKit
import Parse
class resetPasswordVC: UIViewController {
// text field
#IBOutlet weak var emailTxt: UITextField!
// buttons
#IBOutlet weak var cancelBtn: UIButton!
#IBOutlet weak var resetBtn: UIButton!
// clicked cancel button
#IBAction func cancelBtnClick(sender: AnyObject) {
self.dismiss(animated: true, completion: nil)
// dismiss keyboard
self.view.endEditing(true)
}
// clicked reset button
#IBAction func resetBtnClick(sender: AnyObject) {
// hide keyboard
self.view.endEditing(true)
// if email text field is empty
if emailTxt.text!.isEmpty {
// show alert message
let alert = UIAlertController(title: "Email field", message: "is empty", preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
// request for resetting password
PFUser.requestPasswordResetForEmail(inBackground: emailTxt.text!) { (success: Bool, error: Error?) -> Void in
if success {
// show alert message
let alert = UIAlertController(title: "Reset Password Email", message: "has been sent to the email address associated with your account", preferredStyle: UIAlertControllerStyle.alert)
// of ok is pressed call self.dismiss.. function
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: { (UIAlertAction) -> Void in
self.dismiss(animated: true, completion: nil)
})
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
} else {
print(error?.localizedDescription)
}
}
}
// default func
override func viewDidLoad() {
super.viewDidLoad()
// tap to hide keyboard
let hideTap = UITapGestureRecognizer(target: self, action: Selector(("hideKeyboard:")))
hideTap.numberOfTapsRequired = 1
self.view.isUserInteractionEnabled = true
self.view.addGestureRecognizer(hideTap)
}
// hide keyboard function
func hideKeyboard(recognizer: UITapGestureRecognizer) {
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I am sure the issue is something fairly obvious but I have only been working with Swift for 3 months and it is my first programming language. I would really appreciate the help.
Thanks for your time.
SAME ERROR
Hey guys, I've been trying my best to sort this myself but cannot get to grips with it. After the initial response from #Vadian solved the issue of the IBActions, I have still been receiving the same SIGABRT error.
Error Info
2016-10-06 17:18:33.709206 Truegram[13130:1026640] [MobileAssetError:29] Unable to copy asset information from https://mesu.apple.com/assets/ for asset type com.apple.MobileAsset.TextInput.SpellChecker
sign up pressed
2016-10-06 17:18:53.120 Truegram[13130:1026284] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'The class PFUser must be registered with registerSubclass before using Parse.'
I think the above is most relevant to the error and this seems to be vindicated as the error occurs after pressing 'sign up'
I have also added another sign up page, specific to businesses that might be causing the issue.
BusinessSignUp.swift
import UIKit
import Parse
class BusinessSignUpVC: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// profile image
#IBOutlet weak var BusinessAvaImg: UIImageView!
// textfields
#IBOutlet weak var confirmTxt: UITextField!
#IBOutlet weak var passwordTxt: UITextField!
#IBOutlet weak var AddressTxt: UITextView!
#IBOutlet weak var contactNumTxt: UITextField!
#IBOutlet weak var emailTxt: UITextField!
#IBOutlet weak var businessNameTxt: UITextField!
// buttons
#IBOutlet weak var loginBtn: UIButton!
#IBOutlet weak var signupBtn: UIButton!
#IBAction func loginBtnClick(_ sender: AnyObject) {
}
// keyboard frame size
var keyboard = CGRect()
override func viewDidLoad() {
super.viewDidLoad()
// check notifications if keyboard is shown or not
NotificationCenter.default.addObserver(self, selector: #selector(BusinessSignUpVC.showKeyboard(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: Selector(("hideKeyboard:")), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
// declare hide keyboard tap
let hideTap = UITapGestureRecognizer(target: self, action: #selector(BusinessSignUpVC.hideKeyboardTap(_:)))
hideTap.numberOfTapsRequired = 1
self.view.isUserInteractionEnabled = true
self.view.addGestureRecognizer(hideTap)
// profile image circle shape and custom border colour
BusinessAvaImg.layer.borderWidth = 2
BusinessAvaImg.layer.borderColor = UIColor.init(red: 90/255, green: 187/255, blue: 181/255, alpha: 1).cgColor
BusinessAvaImg.layer.cornerRadius = BusinessAvaImg.frame.height/2
BusinessAvaImg.clipsToBounds = true
// declare select image tap
let avaTap = UITapGestureRecognizer(target: self, action: #selector(BusinessSignUpVC.loadImg(_:)))
avaTap.numberOfTapsRequired = 1
BusinessAvaImg.isUserInteractionEnabled = true
BusinessAvaImg.addGestureRecognizer(avaTap)
}
// call picker to select image
func loadImg(_ recognizer: UITapGestureRecognizer) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
picker.allowsEditing = true
present(picker, animated: true, completion: nil)
}
// connect selected image to our image view
private func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
BusinessAvaImg.image = info[UIImagePickerControllerEditedImage] as? UIImage
self.dismiss(animated: true, completion: nil)
}
// hide keyboard if tapped
func hideKeyboardTap(_ recognizer: UITapGestureRecognizer) {
self.view.endEditing(true)
}
// show keyboard
func showKeyboard(_ notification: NSNotification) {
// define keyboard sizes
keyboard = ((notification.userInfo?[UIKeyboardFrameEndUserInfoKey]! as AnyObject).cgRectValue)!
// Do any additional setup after loading the view.
}
// clicked sign up
#IBAction func signupBtnClick(_ sender: AnyObject) {
print("sign up pressed")
// dismiss keyboard
self.view.endEditing(true)
// if fields are empty
if (emailTxt.text!.isEmpty || passwordTxt.text!.isEmpty || confirmTxt.text!.isEmpty || businessNameTxt.text!.isEmpty || AddressTxt.text!.isEmpty || contactNumTxt.text!.isEmpty) {
// alert pop up message
let alert = UIAlertController(title: "Please", message: "fill all fields", preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
// if incorrect password
if passwordTxt.text != confirmTxt.text {
// alert pop up message
let alert = UIAlertController(title: "Attention", message: "incorrect password", preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
// send data to related columns in server
let businessUser = PFUser()
businessUser.username = businessNameTxt.text?.lowercased()
businessUser.email = emailTxt.text?.lowercased()
businessUser.password = passwordTxt.text
businessUser["BusinessUser"] = businessNameTxt.text?.lowercased()
businessUser["Address"] = AddressTxt.text?.lowercased()
businessUser["ContactNumber"] = contactNumTxt.text?.lowercased()
// convert our image for sending to server
let avaData = UIImageJPEGRepresentation(BusinessAvaImg.image!, 0.5)
let avaFile = PFFile(name: "ava.jpg", data: avaData!)
businessUser["ava"] = avaFile
// save data in server
businessUser.signUpInBackground { (success: Bool, error: Error?) -> Void in
if success {
print("registered")
// remember logged user
UserDefaults.standard.set(businessUser.username, forKey: "username")
UserDefaults.standard.synchronize()
// calls login func from AppDelegate.swift class
let appDelegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.login()
} else {
// show alert message
let alert = UIAlertController(title: "Error", message: error!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
let ok = UIAlertAction(title: "OK", style: UIAlertActionStyle.cancel, handler: nil)
alert.addAction(ok)
self.present(alert, animated: true, completion: nil)
}
}
}
// clicked return to log in
#IBAction func businessLoginBtnClick(_ sender: AnyObject) {
self.dismiss(animated: true, completion: nil)
// dismiss keyboard
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
This has now taken me a couple of days attempting to fix, so I would be very appreciative if anyone could help.
The crucial information is
[Truegram.signUpVC signupBtnClick:]: unrecognized selector sent to instance 0x7f9d0700cff0'
In Swift 3 IBActions are supposed to be declared with an underscore to omit the parameter label.
#IBAction func signupBtnClick(_ sender: AnyObject)

Pass data from detail view to master - Swift

I'm new in swift, and I've been searching this answer for weeks, but I still haven't found it:( What I'm building is a master-detail app. It is a reminders app.The user is able to edit those reminders in the detail view, but the problem comes when I try to pass the edited data back to the master view, and add it to an array of arrays that I use as the database. I've tried with an unwind segue, but I don't know how to add in the right place the data that I have passed back. I would really appreciate your help!
//MAIN VIEW
var addMoneyArray = [[Int]]()
class GonMainTableViewController: UITableViewController {
//MARK: - VARIABLES
var recivedData : Int?
//MARK. - IB OUTLETS
#IBOutlet var tableView1: UITableView!
#IBAction func unwindViewController(segue: UIStoryboardSegue){
if(segue.sourceViewController .isKindOfClass(GonDetailViewController))
{
let view2 : GonDetailViewController = segue.sourceViewController as! GonDetailViewController
recivedData = view2.passTxtFieldValue
}
}
enter code here
//VIEW2
class GonDetailViewController: UIViewController {
var passTxtFieldValue : Int?
#IBAction func addBtn(sender: AnyObject) {
var returnMoney = Int(addMoneyTxtField.text!)
returnMoney = passTxtFieldValue
let alertController = UIAlertController(title: "Awesome!", message: "Succesfully saved your data!", preferredStyle: .Alert)
let takePhotoAction = UIAlertAction(title: "OK", style: .Default) { (Alert) -> Void in
self.performSegueWithIdentifier("returnToMain", sender: self)
}
alertController.addAction(takePhotoAction)
presentViewController(alertController, animated: true, completion: nil)
}

Resources