[Journey In App Creation]Post 3- Getting The Data

in #swift6 years ago

Lets get started. We have the design so lets start with that. But first, we need some music. For that, we turn to Spotify. I've been on a bit of a Avicii streak recently so lets continue with that.


Source: Spotify

Now that we got that out of the way, lets go rename the ViewController to a more descriptive name and clean it up. We get this as a result:

We first need to connect the textField to the code. We do that with a IBOutlet. Lets also connect the submit button as an action so that upon touch it, we can get something to happen. To start, I just made pressing the button print out(I tried console.log() to get it to print at first, JS is affecting me) what was in the text field. Its as simple as print(nameTextField.text). Since that works, time to move on.

Lets think of the first case. If there isn't anything in the nameTextField. What do we do? Well, we need to warn the user. So lets add a label that will be hidden upon initial launch and (so far) will only show up if the text field is empty.

This will let us see if the the text field was empty or not(yes, swift doesn't need semicolons, or parentheses around the if statement):

let name = nameTextField.text
if name == ""
{
    print("No Name Entered")
    return
}

By returning out, we ensure that the code after that statement won't be executed if there is no name entered. We can work on handling that particular case later and replace the print("No Name Entered") with a visual handling of the error.

Now, a great song plays so we take a little break. If you haven't listened to Sunset Jesus, give it a listen. Click here to open it on Spotify.

Now we need to get data from an API. We can do everything locally and process it here, but because I don't want to, I'll be writing up some JS and making an API with that. I most likely won't share the process creating the API as this is a lot more focused on the mobile app part of it. If you want me to write how I made the (probably shitty) API, just leave a comment. There is a built in way to fetch data, but I'll be using Alamofire as its a lot easier(and cleaner looking). So lets install it. I'll be using Carthage as my dependency manager as I find it cleaner than CocoaPods. If you want to learn more about Carthage, you can click here.

Once you got it installed, and added to your project, you can import it with import Alamofire.

We can now make a request to the API(currently hosted on http://localhost:8080). It'll be as simple as making a get request. I made it as simple as adding /?userName to the url to get the data. So for example, to get data for me would be http://localhost:8080/?rishi556. So, lets do it. We write it as:

Alamofire.request("http://localhost:8080/?" + name, parameters: nil, headers: nil).responseJSON { response in
            print(response)
}

It would be a good idea to take the start of the url and make it its own variable so we can edit it easily for everywhere if we want to later on. But I'll do that later. But because the App transport securities aren't configured properly, it won't work. So we have to go to the info.plist and edit it to allow it. Lets fix it and rerun it.

If everything was done properly, we'll get some pieces of data back from the API.

I haven't yet written up the active posts part or the SP part so just gotta wait on that.

But what if the name entered isn't a real name? Well, then it returns this message:

Also, don't worry about capitalization as the api server converts it to lowercase when processing through it.

In case we don't get any data back, we need to notify the user. We can tell that we didn't get any if response.value is set to nil. So we can check for that and notify the user and return out with this:

if response.value == nil
            {
                //TODO: Notify User That No Data Was Returned.
                print("There isn't any data returned.")
                return
            }

Now that we are are getting the data, lets simply parse it out and assign it to a few variables. Lets also convert them to a Swift type.

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

Once I get the SP part and Posts part added in, we just have to assign them to a variable too. And I think we are good for today. Here's the entire code so far:

import UIKit
import Alamofire

class NameVC: UIViewController
{

    @IBOutlet weak var nameTextField : UITextField!
    
    override func viewDidLoad()
    {
       
    }
    
    @IBAction func submitButtonAction(_ sender: UIButton)
    {
        let name = nameTextField.text
        
        if name == ""
        {
            //TODO: Notify User That They Didn't Enter A Username
            print("No Name Entred")
            return
        }
        
        Alamofire.request("http://localhost:8080/?" + name!, parameters: nil, headers: nil).responseJSON { response in
            if response.value == nil
            {
                //TODO: Notify User That No Data Was Returned.
                print("There isn't any data returned.")
                return
            }
            
            let responseDict : [String: Any] = response.value as! [String : Any]
            print(responseDict)
            let message = responseDict["message"] as! String
            
            if message == "fail"
            {
                //TODO: Notify User That They Didn't Enter A Correct Username
                print("Username No Exist")
                return
            }
            
            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)
                
            
        }
        
    }
    

}

Next time I'll be working on making the view look nicer and finishing up those TODOs. If you got any questions, throw them in the comments.

Now for the SBI giveaway. Lets make it fun, nothing to do with coding. This is more of a guessing game. Whats my favorite song in Avicii's album Stories(Hint: Its not Sunset Jesus)? All the songs in the album can be found here. First person to get it will get 1 SBI share.

Sort:  

Friggin NERD!!!!!!!!!!

Hi @rishi556, I'm @checky ! While checking the mentions made in this post I noticed that @iboutlet and @ibaction don't exist on Steem. Did you mean to write @boutet and @fraction ?

If you found this comment useful, consider upvoting it to help keep this bot running. You can see a list of all available commands by replying with !help.

Actually, I was correct writing what I wrote. Thats part of the code, not attempts to mention people.

Sorry about that, I plan on making it ignore text in code sections but I can't update it yet (on vacation, not on my computer).

Haha, wasn't expecting a response. Thanks for the explanation.

Here are all the available commands:

  • !delay minutes - tells the bot to wait X minutes before checking your posts.
  • !help - gives a list of commands and their explanations.
  • !ignore username1 username2 - tells the bot to ignore some usernames mentioned in your posts (useful to avoid the bot mistaking other social network accounts for Steem accounts).
  • !mode [regular-advanced-off] - sets the mentions checking to regular (only posts), advanced (posts and comments) or off (no checking). Alternatively, you can write normal or on instead of regular. You can also write plus instead of advanced.
  • !off - shortcut for !mode off.
  • !on - shortcut for !mode on.
  • !state - gives the state of your account (regular, advanced or off).
  • !switch [regular-advanced-off] - same as !mode.
  • !unignore username1 username2 - tells the bot to unignore some usernames mentioned in your posts.
  • !wait minutes - same as !delay.
Any idea on how to improve this bot ? Please contact @ragepeanut on any of his posts or send him a direct message on Discord (RagePeanut#8078).
If you found this comment useful, consider upvoting it to help keep this bot running. You can see a list of all available commands by replying with !help.

!mode advanced

Your account has been set to advanced. You will now get your mentions checked for posts and comments you make.

If you found this comment useful, consider upvoting it to help keep this bot running. You can see a list of all available commands by replying with !help.

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.

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.778 which ranks you at #12270 across all Steem accounts.
Your rank has dropped 27 places in the last three days.

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

Evaluation of your UA score:
  • Only a few people are following you, try to convince more people with good work.
  • The readers like your work!
  • Your contribution has not gone unnoticed, keep up the good work!

Feel free to join our @steem-ua Discord server

Coin Marketplace

STEEM 0.26
TRX 0.11
JST 0.032
BTC 63510.75
ETH 3065.54
USDT 1.00
SBD 3.82