change checkbox status by parse query - swift

Please if you read this, do not ignore it. I'm facing this problem for weeks, and I searched for many solutions, but I couldn't find the answer.
The issue is I made a image button, that shows checkbox. When the view controller is open, parse query retrieve value from class to checkbox action from unchecked to checked if the value is true.
The problem when the view controller is loaded, nothing the checkbox do not change from unchecked to checked.
I hope someone can guide me to solve this problem, I will pray for him in this beautiful night
#IBOutlet var reqPassBox: UIButton!
#IBOutlet var proAccBox: UIButton!
#IBOutlet var showLocBox: UIButton!
#IBOutlet var recMessBox: UIButton!
let checkedImage = UIImage(named: "Checked")! as UIImage
let unCheckedImage = UIImage(named: "Unchecked")! as UIImage
var isBoxClicked:Bool!
override func viewDidLoad() {
super.viewDidLoad()
let query = PFQuery(className: "Privacy")
query.whereKey("user", equalTo: PFUser.current()!)
query.findObjectsInBackground { (object, error) -> Void in
if error == nil {
for objects in object! {
let req = objects["passwordReq"] as! Bool
self.isBoxClicked = req
print(req)
print (self.isBoxClicked)
}
}
}
}
#IBAction func reqPasswordBut(_ sender: Any) {
if isBoxClicked == true {
// isBoxClicked = false
}
else {
// isBoxClicked = true
}
if isBoxClicked == true {
reqPassBox.setImage(checkedImage, for: UIControlState.normal)
}
else {
reqPassBox.setImage(unCheckedImage, for: UIControlState.normal)
}
}

Only one think you have to check, Whether the image is loaded or not?
I used the below code is working perfectly for me
Swift 3.0
#IBOutlet weak var sampleBUtton: UIButton!
sampleBUtton.setImage(UIImage.init(named: "NYT"), for: UIControlState.normal)

Related

When I tap the image I want to go to the URL

I am trying that when I press the image it takes me to the link
I have this:
class CoverPillCell: TableViewCell {
#IBOutlet weak var imagePill: UIImageView!
#IBOutlet weak var imagenButton: UIButton!
this contains variables that later in the load function call the remoteconfig
height = CGFloat(promoPill?.image_height ?? 0)
width = CGFloat(promoPill?.image_width ?? 0)
target_url = promoPill?.target_url ?? ""
position = promoPill?.position ?? 0
if enabled == true {
enabled = ((promoPill?.enabled) != nil)
}
//This is what I'm trying to when tap go to the target url which is configured on the remote config
if imagenButton.isUserInteractionEnabled == true {
self.imagenButton.addTarget(self, action: #selector(tapPill(_:)), for: .touchUpInside)
}
And in the IBAction I'm trying this:
#IBAction func tapPill(_ sender: UIButton) {
let promoPill = getPromoPill()
target_url = promoPill?.target_url ?? ""
}
Maybe this link can help you
You have to do something like this ->
let myURL = URL(string:"https://www.apple.com")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)

How to get the current Title of a button in Swift?

What am I doing wrong?
I get this error:
let letterString = sender.title(for: .normal)! // Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
when I tried to get the title of a button in swift like below:
import UIKit
class ViewController: UIViewController {
// My IBOutlets
#IBOutlet var treeImageView: UIImageView!
#IBOutlet var correctWordLabel: UILabel!
#IBOutlet var scoreLabel: UILabel!
// My Outlet Collection
#IBOutlet var letterButtons: [UIButton]!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// Begin the round.
newRound()
}
var listOfWords = ["estufa", "nevera", "computadora", "empanada", "chuleta", "camarones", "brincar", "correr", "caminar", "tigre", "jirafa", "mono", "kisseemmee", "Tampa", "Orlando"]
let incorrectMovesAllowed = 7
let totalWins = 0
let totalLosses = 0
// My IBActions
#IBAction func letterButtonPressed(_ sender: UIButton) {
sender.isEnabled = false
let letterString = sender.title(for: .normal)! // Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value
let letter = Character(letterString.lowercased())
currentGame.playerGuessed(letter: letter)
updateUI()
}
var currentGame: Game!
func newRound() {
let newWord = listOfWords.removeFirst()
currentGame = Game(word: newWord, incorrectMovesRemaining: incorrectMovesAllowed, guessedLetters: [])
updateUI()
}
func updateUI() {
scoreLabel.text = "Wins: \(totalWins), Losses: \(totalLosses)"
treeImageView.image = UIImage(named: "Tree \(currentGame.incorrectMovesRemaining)")
}
}
// Game.swift file code:
import Foundation
struct Game {
var word: String
var incorrectMovesRemaining: Int
var guessedLetters: [Character]
mutating func playerGuessed(letter: Character) {
guessedLetters.append(letter)
if !word.contains(letter) {
incorrectMovesRemaining -= 1
}
}
}
I'm a newbie. This is my first program. I appreciate if you code the solution.
You can get the title of the UIButton using titleLabel property. Check the below code.
sender.titleLabel?.text
As the above code returns optional, you can use optional chain to safely get the string
if let titleLabel = sender.titleLabel {
let title = titleLabel.text
}
OR
You can also use the currentTitle property as below.
sender.currentTitle
You can use:
sender.titleLabel.text

displaying user email on viewcontroller gives optional"email adress" [duplicate]

This question already has answers here:
How to remove optional text from json Result In swift
(3 answers)
Optional Text in Alert in ResetPassword - iOS Project using Swift
(2 answers)
Closed 1 year ago.
So I'm using firebase Authentication in my ios app, and I want to display the email address, and Username in UIlabels on a viewcontroller. But when i display the value of Auth.auth().email on a UIlabel, the Label would show Optional"email adress".How do i get rid of the Optional and also how to allow the user to have a display name in firebase Authentication?
import Firebase
import FirebaseAuth
class ProfileViewController: UIViewController {
#IBOutlet weak var profiepic: UIImageView!
#IBOutlet weak var UsernameLabel: UILabel!
#IBOutlet weak var EmailLabel: UILabel!
#IBOutlet weak var league: UILabel!
#IBOutlet weak var Achievements: UIButton!
#IBOutlet weak var resetpasswd: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
UsernameLabel.layer.borderColor = UIColor.black.cgColor
EmailLabel.layer.borderColor = UIColor.black.cgColor
league.layer.borderColor = UIColor.black.cgColor
Achievements.layer.cornerRadius = 55/2
resetpasswd.layer.cornerRadius = 55/2
resetpasswd.layer.borderColor = UIColor.black.cgColor
displayinfo()
}
func displayinfo() {
let user = Auth.auth().currentUser
if let user = user {
// The user's ID, unique to the Firebase project.
// Do NOT use this value to authenticate with your backend server,
// if you have one. Use getTokenWithCompletion:completion: instead.
let email = user.email
let photoURL = user.photoURL
EmailLabel.text = "Email: \(email)"
// ...
}
}
/*
// 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.destination.
// Pass the selected object to the new view controller.
}
*/
}
You need to use if or guard to display string info properly.
Using if:
func displayinfo() {
let user = Auth.auth().currentUser
if let user = user {
if let email = user.email {
EmailLabel.text = "Email: \(email)"
}
if let photoURL = user.photoURL {
...
}
// ...
}
}
Using guard:
func displayinfo() {
guard let user = Auth.auth().currentUser else {
print("No user info found")
return
}
if let email = user.email {
EmailLabel.text = "Email: \(email)"
//EmailLabel.text = "Email: " + email
}
if let photoURL = user.photoURL {
...
}
// ...
}
Let me know if you have any issue in these solutions.
Apart from this, I would rather write UIViewController in this manner which seems to be a more clearer approach.
class ProfileViewController: UIViewController {
#IBOutlet weak var profiepic: UIImageView!
#IBOutlet weak var lblUsername: UILabel! {
didSet {
lblUsername.layer.borderColor = UIColor.black.cgColor
}
}
#IBOutlet weak var lblEmail: UILabel! {
didSet {
lblEmail.layer.borderColor = UIColor.black.cgColor
}
}
#IBOutlet weak var lblLeague: UILabel! {
didSet {
lblLeague.layer.borderColor = UIColor.black.cgColor
}
}
#IBOutlet weak var btnAchievements: UIButton! {
didSet {
btnAchievements.layer.cornerRadius = 55/2
// For button height, instead of 55 here you can use, btnAchievements.bounds.height / 2 or use constrain also to change button height when bound changes
}
}
#IBOutlet weak var btnReset: UIButton! {
didSet {
btnReset.layer.cornerRadius = 55/2
btnReset.layer.borderColor = UIColor.black.cgColor
}
}
private var currentUser: AuthUser? {// Type of Auth.auth().currentUser
didSet {
// Use above code for displayInfo or simply call displayInfo from here
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.currentUser = Auth.auth().currentUser
}
...
}
I hope this would help you designing other UIViewControllers as well.

Swift menu not showing on right navigation button click

New to Swift. I have a simple UI: put a UINavigationBar on top of a UIWebView, and a the right bar button item to have an action that shows a menu, to allow the use choose different pages to show in the web view.
Show the view controller looks like:
class ViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
#IBOutlet weak var menu: UIBarMenuItem!
#IBOutlet weak var viewnav: UIView!
override func viewDidLoad() {
super.viewDidLoad();
let url = URL(string:"about:blank")
let req = URLRequest(url:url!)
webView.loadRequest(req)
}
#obj func dummy(){
}
#IBAction func MenuShow(sender: UIBarButtonItem){
let menu = UIMenuController.shared
viewnav.becomeFirstResponder()
menu.setTargetRect(viewnav.frame, in:viewnav)
let dummy = UIMenuItem(title:"Dummy", action: #selector(dummy))
menu.menuItems = [dummy]
menu.setMenuVisible(true, animated: true)
//for test only; should move to menu item actions
let url = URL(string:"https://www.apple.com")
let req = URLRequest(url:url!)
webView.loadRequest(req)
}
}
(I have connected the web view, the bar button to the UI object; for viewnav I tried adding a new dummy view in Main.storyboard or using the existing navigation bar, both have the same result)
The resulting app shows the empty page and when I hit the menu button, jumps into Apple's home page, so the above code runs as expected. But the menu didn't show up, so what is wrong for the code above?
(there are a few other simular questions like this, but they didn't seem to solving the problem)
This answer gives the solution:
override var canBecomeFirstResponder: Bool {
return true
}
And add this line to the viewDidLoad method
view.becomeFirstResponder()
Full version:
class ViewController: UIViewController {
#IBOutlet weak var webView: UIWebView!
#IBOutlet weak var menuButton: UIBarMenuItem!
override func viewDidLoad() {
super.viewDidLoad();
let url = URL(string:"about:blank")
let req = URLRequest(url:url!)
webView.loadRequest(req)
view.becomeFirstResponder()
let menu = UIMenuController.shared
let dummy = UIMenuItem(title:"Dummy", action: #selector(dummy))
menu.menuItems = [dummy]
}
override var canBecomeFirstResponder: Bool {
return true
}
#obj func dummy(){
let url = URL(string:"https://www.apple.com")
let req = URLRequest(url:url!)
webView.loadRequest(req)
menu.setMenuVisible(true, animated: false)
}
#IBAction func MenuShow(sender: UIBarButtonItem){
let menu = UIMenuController.shared
let bv = menuButton.value(forKey: "view") as? UIView
menu.setTargetRect(bv!.frame, in:view)
menu.setMenuVisible(true, animated: true)
}
}

swift save multiple manage objects

Having issues saving my manage objects within my code. For some reason when i place data in the first view controller everything works well. For instance
I place new categories such as "Fruits", "Dairy", "Meats". The first view controller takes the data. When I click on the specific item such as "Dairy", and put in "Milk" for items within that section. If I go back to the previous view controller and click on "Meats", I see the same data i put in under "Dairy". How do i properly manage my NSManage objects.
Here is my code below.
import UIKit
import CoreData
class HomeSpecificItemViewController: UIViewController {
var selectedItem : [Items] = []
#IBOutlet weak var itemNameTextField: UITextField!
#IBOutlet weak var brandNameTextField: UITextField!
#IBOutlet weak var caloriesTextField: UILabel!
#IBOutlet weak var priceTextField: UILabel!
#IBOutlet weak var amountTextField: UITextField!
#IBOutlet weak var threshHoldNumberField: UITextField!
#IBOutlet weak var stepper: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
stepper.wraps = true
stepper.autorepeat = true
stepper.maximumValue = 10
// Do any additional setup after loading the view.
}
#IBAction func saveButton(sender: AnyObject) {
let context = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let itemDescription = NSEntityDescription.insertNewObjectForEntityForName("Items", inManagedObjectContext: context) as! Items
itemDescription.setValue(itemNameTextField.text, forKey: "Items")
itemDescription.setValue(brandNameTextField.text, forKey: "Items")
do {
try context.save()
}catch _ {
}
/*
let request = NSFetchRequest(entityName: "Items")
let results : [AnyObject]?
do {
results = try context.executeFetchRequest(request)
}catch _ {
results = nil
}
if results != nil {
self.itemDescription = results as! [Items]
}
*/
}
#IBAction func cancelPressed(sender: AnyObject) {
self.dismissViewControllerAnimated(true, completion: nil)
}
#IBAction func increaseNumberStepper(sender: UIStepper) {
threshHoldNumberField.text = Int(sender.value).description
}
}
Do you have a specific view controller for each category? If so, what you have to do is add predicates to your more specific view controllers.
Something like:
var request = NSFetchRequest(entityName: "Food")
request.predicate = NSPredicate(format: "category == %#", "Meat")
meats = try! context.executeFetchRequest(request)
This would return an array of all Food objects whose category atribute holds the string "Meat".
I was saving my data to core data without properly declaring the manage context and without assigning the text labels to the core data object.
issue resolved!