[Journey In App Creation]Post 4- Showing The Errors

in #swift8 years ago (edited)

So now that we got the data, we left some TODOs to handle at a later time. Lets start completing them. They aren't hard, I just wanted to finish up the data retrieval and parsing out before going onto other topics.

Lets start with the label that'll show errors. Lets add that onto our view and then connect it.

Screen Shot 2018-09-06 at 8.14.33 PM.png

if name == ""
        {
            //TODO: Notify User That They Didn't Enter A Username
            errorLabel.text = "Please Input A Name"
            print("No Name Entred")
            return
        }

Running the app and pressing submit without putting in a name now works. But we run into another problem. When we first launch the app up, the label is there just saying "Error Label". So we need to hide it. When that screen is launched, the code within viewDidLoad happen. So we can set the label to be hidden when its launched. So lets do that. All we need to do is add : errorLabel.isHidden = true inside viewDidLoad.

But doing that will cause a problem. It'll remain hidden even when we change the text inside it to show the user the error. To do that, we unhide it. Thats as simple as errorLabel.isHidden = false. So all we would need to do is put that a line before changing the text of it.

Now if the user keeps pressing the button with no text inside the textField, the message won't change. To show the user that, we'll flash the screen red for 0.01 seconds. To do that, we'll first set the view's background color to red, the on a thread we have something thats done after 0.01 seconds. Thats written as:

self.view.backgroundColor = .red
DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
     self.view.backgroundColor = .white
     }

We get a result like this:


Due to the speed of the flash, its near impossible to see it with a gif. You can sort of make it out.

Now we are just doing something similar everywhere else, just with a different message. So we can make this into a function so we don't have to keep repeating ourselves. Lets do that.

func showError(message: String)
    {
        self.errorLabel.isHidden = false
        errorLabel.text = message
        self.view.backgroundColor = .red
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            self.view.backgroundColor = .white
        }
    }

Functions in swift are declared with func. The message: String part is the parameter. It shows that the message paramour that you pass has to be of type String.

We can call that function with : showError(message: "Please Input A Name"). Lets do that for all the other errors, but replacing the message with what we need the message to be.

After we do that, we just have to rehide the label if we do get data back and no errors happen. So lets put the code to hide the label right before we start parsing the data out.

Lets run some tests. Yup, it all works out perfectly. Thats all for the day guys. Just some simple stuff. On the next post I'll start displaying the data. Here's all of what we have so far:

import UIKit
import Alamofire

class NameVC: UIViewController
{

    @IBOutlet weak var nameTextField : UITextField!
    @IBOutlet weak var errorLabel: UILabel!
    
    override func viewDidLoad()
    {
       errorLabel.isHidden = true
    }
    
    @IBAction func submitButtonAction(_ sender: UIButton)
    {
        let name = nameTextField.text
        
        if name == ""
        {
            showError(message: "Please Input A Name")
            return
        }
        
        Alamofire.request("http://localhost:8080/?" + name!, parameters: nil, headers: nil).responseJSON { response in
            if response.value == nil
            {
                self.showError(message: "We didn't get any data back.")
                return
            }
            
            let responseDict : [String: Any] = response.value as! [String : Any]
            print(responseDict)
            let message = responseDict["message"] as! String
            
            if message == "fail"
            {
                self.showError(message: "User doens't exist")
                return
            }
            
            self.errorLabel.isHidden = true
            let vp = (responseDict["vp"] as! NSString).floatValue
            let liquidSteem = (responseDict["liquidSteem"] as! NSString).floatValue
            let savingSteem = (responseDict["savingSteem"] as! NSString).floatValue
            let liquidSBD = (responseDict["liquidSBD"] as! NSString).floatValue
            let savingSBD = (responseDict["savingSBD"] as! NSString).floatValue
            
            print(vp, liquidSteem, savingSteem, liquidSBD, savingSBD)
                
        }
        
    }
    
    func showError(message: String)
    {
        self.errorLabel.isHidden = false
        errorLabel.text = message
        errorLabel.textAlignment = .center
        self.view.backgroundColor = .red
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.01) {
            self.view.backgroundColor = .white
        }
    }
    

}

Edit: I forgot to put in the contest for SBI. So um, here's one. Other than Carthage, whats the other popular dependency manager for iOS apps(hint it begins with the same letter)?

Sort:  

You got voted by @votefun thanks to Princess. To support development, check out @rishi556. Hosted on the @cryptowithincin discord.

You got voted by @curationkiwi thanks to Princess! This bot is managed by @KiwiBot and run by @rishi556, you can check both of them out there. To receive maximum rewards, you must be a member of @KiwiBot. To receive free upvotes for yourself (even if you are not a member) you can join the KiwiBot Discord linked here and use the command !upvote (post name) in #curationkiwi.

This post has received a 3.13 % upvote from @drotto thanks to: @curationkiwi.

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by Princess from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, someguy123, neoxian, followbtcnews, and netuoso. The goal is to help Steemit grow by supporting Minnows. Please find us at the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: 50SP, 100SP, 250SP, 500SP, 1000SP, 5000SP.
Be sure to leave at least 50SP undelegated on your account.

Steemin-comment-header.png

Congratulations🎉, You received a upvote👍 from @Atombot - Steemin Community Bot. Thank you for using our bot🤖 and Joined our Steemin Server.


If you want to learn about steemit and want to upvotes. Just Join our Steemin Community 👇

leftside arrow Steemin rightside arrow

👉 Delegation to the Atombot 👈

1 SP | 5 SP | 10 SP | 15 SP | 20 SP | 50 SP | 100 SP | Custom SP

Steemin-comment-footer.png

Hi @rishi556!

Your post was upvoted by @steem-ua, new Steem dApp, using UserAuthority for algorithmic post curation!
Your UA account score is currently 2.791 which ranks you at #12224 across all Steem accounts.
Your rank has improved 36 places in the last three days (old rank 12260).

In our last Algorithmic Curation Round, consisting of 325 contributions, your post is ranked at #317.

Evaluation of your UA score:
  • Only a few people are following you, try to convince more people with good work.
  • Try to show your post to more followers, for example via networking on our discord!
  • Try to work on user engagement: the more people that interact with you via the comments, the higher your UA score!

Feel free to join our @steem-ua Discord server

Coin Marketplace

STEEM 0.04
TRX 0.32
JST 0.100
BTC 64942.32
ETH 1923.05
USDT 1.00
SBD 0.39