Generate swift models directly from url

Majority of the mobile apps communicates with api. We are always writing get and post request for every app and for every api. It is a redundant job That cannot be skipped.

But we can sure automate it.

Introducing veda-apps . It is a collection of tools used frequently in ios. There are many features yet to come. But for now lets us generate our files from url.

Open terminal: Enter

gem install veda-apps , or sometimes, sudo gem install veda-apps

now enter: veda

you should see something like this

Screen Shot 2018-01-23 at 4.38.59 PM

We can generate model with url, but some url needs headers like authorization, api-keys so in order to manage all of it. first we create a config file. which will contain all the credential.

veda generate model config

This will create a config.json file in the current directory. config file contains placeholders elements that need to be updated by you.


{
"url": "url",
"headers": {
"Authorization": "token",
"OtherHeaders": "add as your need"
}
}

replace “url” with your url and headers according to your need.

veda generate model

=> This will load your config file, fetch the json from url and parse it. It will generate all the class in different files in current directory.

=> You can create model from json file as well. suppose you have input.json file that contains the json response.

veda generate model -f  input.json

This will read json from input.json and parse it.

But it does not end here. It supports the realm as well.

veda generate model –realm

veda generate model -f input.json –realm

it generates all ready made class files that have the default values. And is ready to be saved in the realm.

since in swift we write camelCased. But data from ruby or php like servers give us in snake_case format. All variable names are automatically changed to camelCased.

 

And lastly,

make sure your podfile have this.

import ObjectMapper
import RealmSwift

in your pod file. and pod install is success

you can change the default values according to your needs.

Thanks.

 

 

Advertisements

QR Scanner in swift in 5 minutes.

Implementing QR scanner has never been so easy. I worte a  gem  veda-apps  to automate some task in ios.   It is still in development though and has many Promising features yet to come.

Qr Scanner in ios.

open Terminal, and enter

  gem install veda-apps

Or sometimes, sudo gem install veda-apps

and you are all ready to go.

    1. Create New Xcode project.
    2. Rdd button and action to open qrscanner.
    3. gem install veda-apps. ( in some cases sudo gem install veda-apps )
    4. Open terminal, enter the following command.

veda generate qr -f path_to_viewController

Note: path_to_viewcontroller is the view controller from where you want to open qr scanner

Right click in your project directory -> Add files to project ->  add following files.

  1. UIViewControllerExtension.swift
  2. VedaQr.storyboard
  3. VedaQRScannerViewController.swift

In your story board add a button and extend an action for that button.

Screen Shot 2018-01-18 at 8.26.55 PM

add following code to open scanner inside the action.


@IBAction func openQr(_ sender: UIButton) {
self.scan()
}

Yeaah! all the permission are handled by veda-apps.

want to learn more: https://github.com/Iccr/VedaApp/wiki/QRScanner

Enjoy.

Custom json with Juilder

Using jbuilder for customize json views is a great experience. also I have been writing the jbuilder in a long way. just today i found shortcuts way to write the same this. The length of the code dramatically reduced. Plus jbuilder support for partial is the best thing one could dream of.

previously the my code to render the array of books was  was like this.

json.data do
  json.books @books do |book|
    json.id book.id
    json.name book.name
    json.author book.author
    json.condition book.condition
    json.genere book.genere
    json.grade book.grade
    json.price book.price
    json.publication book.publication
    json.latitude book.latitude
    json.longitude  book.longitude
    json.address book.address
    json.donate book.donate
    json.exchange book.exchange

  end
end

Then I found the shortcut way for the same thing.

json.data do
  json.books @books do |book|
    json.(book, :id, :name, :author, :condition, :genere, :grade, :price, :publication, :latitude, :longitude, :address, :donate, :exchange)
  end
end

See that large chunk reduced to simple lines. Just Wow.. 🙂

then I wrote a partial for that book Under the name _book.json.jbuilder

    json.(book, :id, :name, :author, :condition, :genere, :grade, :price, :publication, :latitude, :longitude, :address, :donate, :exchange)

and in index.jbuilder.json

  json.data do
   json.books @books do |book|
     json.partial! book
   end
  end

and thats it. The same partial can be reuse in index, create, update and delete views.

and the magic is that if we have to add or change any attribute, just do it in partial. all views will automically updated. yeeaa 😀

The remote end hung up unexpectedly

Sometimes, we faced an annoying problem like this one while trying to clone my BitBucket Repo.

 git clone git@bitbucket.org:veda_the_ram/veda-ios.git
  Cloning into 'veda-ios'...
  remote: Counting objects: 1688, done.
  remote: Compressing objects: 100% (1272/1272), done.
  Connection to bitbucket.org closed by remote host.00 KiB/s
  fatal: The remote end hung up unexpectedly
  fatal: early EOF
  fatal: index-pack failed

Tried increasing the postBuffer size as suggested in different stack overFlow answers. But it did not work out for me. After some research, I found the solution.

  
  git config --global core.compression 9

changing the compression quality  did the trick. Hmm.. ??

Cool Animation In UITableView

Animation in iOS are the heart of the user experience. We can add cool animation with few lines of code. I would like to share a piece of UITableViewAnimation here.

ezgif-com-video-to-gif

After all the cells are displayed normally in table view. Create a simple function called AnimateTableView.

 
func animateTableView() {
        tableview.reloadData()
        let cells = tableview.visibleCells
        let tableHeight = tableview.bounds.size.height
        
        cells.forEach({
            $0.transform = CGAffineTransform(translationX: 0, y: tableHeight)
        })
        
        var delayCounter = 0
        
        cells.forEach { (cell) in
            UIView.animate(withDuration: 1.75, delay: (Double(delayCounter) * 0.05), usingSpringWithDamping: 0.8, initialSpringVelocity: 0, options: .curveEaseOut, animations: {
                cell.transform = CGAffineTransform.identity
            }, completion: nil)
            delayCounter += 1
        }
    }

Just call that function in viewWillAppear or whereEver you want the show the animation.

cheers 

How to search for Crazy People…

Some times Its so much useful to have a search feature in our apps. It’s so much easy to search the table view in swift.

I have a basic project already setup which  a table view as a list of names.

Screen Shot 2016-12-19 at 8.23.14 PM.png

I have defined two outlets for UITextField and UITableView in my ViewController Class.

import UIKit

class ViewController: UIViewController {
    
    @IBOutlet weak var txtSearch: UITextField!
    @IBOutlet weak var tableView: UITableView!
    
    let names: [String] = [
        "Ccr", "Shishir", "Da ri",
        "Bibek", "Manoj", "Amrit",
        "An Gee", "Dee J", "Ajeet",
        "Ashik", "Be Nod", "Samina",
        "guru", "aarko guru", " aani guru ko dup"
    ]
    var searchText: String = ""
    
    var filterednames: [String]  {
        let searchText = self.searchText.lowercased()
        return names.filter({
            name in
                return searchText.isEmpty || name.lowercased().contains(searchText)
        }).sorted(by: { (name, _) -> Bool in
            return name.hasPrefix(searchText) ?? false
        })
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        txtSearch.addTarget(self,
                            action: #selector(ViewController.filter(sender:)),
                            for: UIControlEvents.editingChanged
        )
    }
    
    func filter(sender: UITextField) {
        searchText = sender.text!
        tableView.reloadData()
    }
}


extension ViewController: UITableViewDataSource {

    func tableView(_ tableView: UITableView,
                   numberOfRowsInSection section: Int) -> Int {
        return filterednames.count
    }
    
    func tableView(_ tableView: UITableView,
                   cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()
        let name = filterednames[indexPath.row]
        cell.set(name: name)  // see extension below.
        return cell
    }
}

extension UITableViewCell {
    func set(name: String) {
        self.textLabel?.text = name
    }
}

So, That’s how we find crazy people.

Choosing you default editor for git in unix system.

I used to love “nano” for a long time. But recently, I gave a try to vi and I am quite happy with it.

We can change our default editor in unix system with simple command.

git config --global core.editor "nano"   --> # if you love nano

git config --global core.editor "vim"   -->  # if you love vim

Presenting TransLucent Modal

POPUp view with a translucent background is simple way to add a cool effect on our app.

My storyBoard settings is show in this figure.

Its a simple view with little bit of opacity. Note that Alpha value is 0.8 and its backgroundColor is Black.

popUp view is simply just an another view.

screen-shot-2016-11-20-at-11-23-51-am

First grab that popUp viewController.

 let popUp = UIStoryboard.storyBoardWith(sbType: .ClubDetail).viewController() as RatingPopUp2

Then set the Modal presentation style. It defines how this modal should be presented.

 popUp.modalPresentationStyle = UIModalPresentationStyle.OverCurrentContext

Since I have  all viewControllers setup in a tabBarController, I want to present this view from the rootViewController, So that the tab bar settings remains behind this view.

So, I grab the RootViewcontroller and present this view from it.

 
let rootViewController = UIApplication.sharedApplication().keyWindow?.rootViewController
 rootViewController?.presentViewController(popUp, animated: true, completion: nil)

Result: 

A Sleek effect 🙂

bestresult

 

Find if user is using iPAD or iPhone in swift

Many times we have to know if user is on iPad and iPhone. The most simple example is showing alerts and actionSheet. ActionSheets are cool when you have a bunch of actions. But iPad doesn’t support ActionSheets. In such case we may show alerts in iPad and actionSheet in iPhone.

 

UIAlertControllerStyle determines how the alerts are shown.

var presentationStyle: UIAlertControllerStyle = .ActionSheet
        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad) {
            presentationStyle = .Alert
            // Looks like user is using iPad...
        }
        // now show alerts using presentationStyle. and forget what device user is using.

Rounding a double value to x number of decimal places in swift

A little extension I wrote in Swift to round off the numbers to required number of decimal places.

 
extension Double {
    func roundOff(precision: Double) -> Double {
        let multiplier = pow(10.0, precision)
        let y = Double(round(multiplier * self) / multiplier)  // round function takes decimal value and returns double without decimals. round(123.456) --> 123
        return y
        }
}

 

Usage:

 
let x = 123.456

x.roundOff(1)  --> 123.5

x.roundOff(2) --> 123.46

x.roundOff(2) --> 123.456