Search This Blog

Showing posts with label iOS. Show all posts
Showing posts with label iOS. Show all posts

Sunday, August 26, 2018

Test iOS Project for tutu.ru. Part 1

Description

Full task description can be found here on GitHub


What need to be done

1. Application should have TabBar with two tabs:
  1. Schedule ("Расписание") 
  2. About ("О приложении")

2. Schedule Screen ("Расписание")
The screen should allow you to select:
  1. Departure station(Станция "отправления")
  2. Arrival station(Станция "прибытия")
  3. Date of departure(Дату отправления)

3. Station List Screen ("Экран выбора станции")
The station selection screen must be built on the basis of UITableView and it should:
Contain the general list of stations (see the attached file), grouped by the value of "Country, City". A complete list of groups and elements should be presented on one screen, with the ability to scroll through the entire content.
Provide the ability to search for part of the name (both initial and incoming, regardless of the register). Search must be performed on the same screen, where the list of stations is presented, using the UISearchController.

4. Station Detail Screen ("Детальной информация о конкретной станции")
Display detailed information about a particular station (naming and its full address, including city, region and country).

5. About Screen ("О приложении")
In this section you need to post information about:
  1. Author
  2. Application Version
Input data
{
  "citiesFrom" : [  ], //массив пунктов отправления
  "citiesTo" : [  ] //массив пунктов назначения
}
City object
{
 "countryTitle" : "Россия", //название страны
 "point" : { //координаты города
  "longitude" : 50.64357376098633,
  "latitude" : 55.37233352661133
 },
 "districtTitle" : "Чистопольский район", //название района
 "cityId" : 4454, //идентификатор города
 "cityTitle" : "Чистополь", //название города
 "regionTitle" : "Республика Татарстан", //название региона
 "stations" : [...] //массив станций
}
Station object
{
 "countryTitle" : "Россия", //название страны (денормализация данных, дубль из города)
 "point" : { //координаты станции (в общем случае отличаются от координат города)
  "longitude" : 50.64357376098633,
     "latitude" : 55.37233352661133
 },
 
 "districtTitle" : "Чистопольский район", //название района
 "cityId" : 4454, //идентификатор города
 "cityTitle" : "город Чистополь", //название города
 "regionTitle" : "Республика Татарстан", //название региона
 
 "stationId" : 9362, //идентификатор станции
 "stationTitle" : "Чистополь" //полное название станции
}


Sunday, July 1, 2018

Generating random and using It in Swift

Default Methods

For generating random numbers in swift, the following functions are used:
  • arc4random() returns a random integer number in the range of 0 to 4 294 967 295 (it is UInt32.max)
  • drand48() returns a random float point number in the range of 0.0 to 1.0
  • arc4random_uniform(N) returns a random integer number in the range of 0 to N - 1

Let's see examples of how this functions work:
arc4random() // 107985684

drand48() // 0.3964647737602753

arc4random_uniform(10) // 4
But what if we need to implement more advanced requirements for generating random numbers. Let's explore possible situations where we generating random numbers and using it.

Generate Random Integer with Upper Bound

For generating random integer in range between 0 and upper bound we use function

rc4random_uniform(N)

This function will return random integer number in the range of 0 to N - 1. So, for example, if N = 42 then maximum number that can be generate will be 41 and minimum will be 0.
rc4random_uniform(42)
This function takes one parameter of type UInt32 and returns value of type UInt32
func arc4random_uniform(_ __upper_bound: UInt32) -> UInt32
So, if you work with values of type Int you have to convert values to type UInt32 when parameter passed to function and convert back to Int when getting result.
let number: Int
number = Int(arc4random_uniform(42))

let inputNumer: Int = 100
let outputNumber: Int
outputNumber = Int(arc4random_uniform(UInt32(inputNumer)))
It is not very handy always do this conversion when generating random numbers. Let's make a function for this:
func random(n: Int) -> Int {
    return Int(arc4random_uniform(UInt32(n)))
}

let n: Int
n = random(n: 99)
This function takes one parameter of type Int and return result in range between 0 and N-1 of type Int.

To make it more useful we can create extension for type Int and generating of random integers will be availbale everywhere in code. We also can check for sign before passed parameter because UInt32 type is unsigned type and in case of negative value passed we need to get absolute value from input passed parameter. This method is static and will be available for whole Int type, there is no need to create instance of Int type.
extension Int {
    
    static func random(_ n: Int) -> Int {
        if n < 0 {
            return -Int(arc4random_uniform(UInt32(abs(n))))
        } else if n > 0 {
            return Int(arc4random_uniform(UInt32(n)))
        } else {
            return 0
        }
    }
}

Int.random(-100) // return in range between -99 and 0
But we can create also an instance method in extension. In this case instance of Int type will be used as upper bound for random number generation function.
extension Int {
   
    func random() -> Int {
        if n < 0 {
            return -Int(arc4random_uniform(UInt32(abs(self))))
        } else if n > 0 {
            return Int(arc4random_uniform(UInt32(self)))
        } else {
            return 0
        }
    }
}

65.random()

Monday, October 23, 2017

iOS Swift. How to Animate a Bar Button Item

Today I will show you how to make animated bar buttons and make it with coding. First of all we need icons for our navigation bar. Let's get them from google material design icons.

Google Material Design Icons

Adding icons to project


The only thing that we make with Storyboard is embed our view controller in navigation controller. We need it for navigation bar as container for bar buttons.


Declare two bar button items
var settingsBarButton: UIBarButtonItem?
    
var favoriteBarButton: UIBarButtonItem?

And Bool variable for switch icon of favourite button.
var favorite: Bool = false

Creating images from Assets. One image for settings icon and two images for favourite icon (favourite and unfavourite).
let settingsImage = UIImage(named: "ic_settings_48pt")?.withRenderingMode(.alwaysTemplate)
let favoriteBorderImage = UIImage(named: "ic_favorite_border_48pt")?.withRenderingMode(.alwaysTemplate)
let favoriteFullImage = UIImage(named: "ic_favorite_48pt")?.withRenderingMode(.alwaysTemplate)

Inside viewDidLoad method let's create UIButton, configure it and initialize settings bar button item with this UIButton. We put it to the left part of navigation item of view controller.
let settingsButton = UIButton(type: .system)
settingsButton.tintColor = .black
settingsButton.setImage(self.settingsImage, for: .normal)
settingsButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
settingsButton.addTarget(self, action: #selector(settingsButtonTapped), for: .touchUpInside)
self.settingsBarButton = UIBarButtonItem(customView: settingsButton)
self.navigationItem.setLeftBarButton(settingsBarButton, animated: false)

It is touch handler for button. Here we make animation. There are two steps:

  1. Rotate view to some angle
  2. With animation we restore initial view rotation as it was before first rotation

@objc func settingsButtonTapped(_ sender: UIButton) {
    self.settingsBarButton?.customView?.transform =
        CGAffineTransform(rotationAngle: CGFloat(CGFloat.pi * -3/4))
    UIView.animate(withDuration: 0.8) {
        self.settingsBarButton?.customView?.transform = .identity
    }
}

The same for favourite bar button. Initially we create it with favourite empty icon (unfavourite). We put it to the right part of navigation item of view controller.
let favoriteButton = UIButton(type: .system)
favoriteButton.tintColor = .black
favoriteButton.setImage(self.favoriteBorderImage, for: .normal)
favoriteButton.frame = CGRect(x: 0, y: 0, width: 30, height: 30)
favoriteButton.addTarget(self, action: #selector(favoriteButtonTapped), for: .touchUpInside)
self.favoriteBarButton = UIBarButtonItem(customView: favoriteButton)
self.navigationItem.setRightBarButton(favoriteBarButton, animated: false)

Touch handler for favourite button. The same logic as before, but here we use other type of transformation(previously we use rotation), now we use scaling transformation:
  1. Change button scale.
  2. Restore button scale with animation. Also inside animation we change icon of button. 
Here we use spring animation. It means that here will be appear special effects during animations. Such as velocity and damping changing and etc.
@objc func favoriteButtonTapped(_ sender: UIButton) {
        self.favoriteBarButton?.customView?.transform = CGAffineTransform(scaleX: 0, y: 0)
        UIView.animate(withDuration: 0.5,
                       delay: 0.0,
                       usingSpringWithDamping: 0.6,
                       initialSpringVelocity: 10,
                       options: .curveEaseInOut,
                       animations: {
                        self.favorite = !self.favorite
                        let image = self.favorite ? self.favoriteFullImage : self.favoriteBorderImage
                        if let button = self.favoriteBarButton?.customView as? UIButton {
                            button.setImage(image, for: .normal)
                        }
                        self.favoriteBarButton?.customView?.transform = .identity
        }, completion: nil)
}

How it all work





GitHub Link

Sunday, October 22, 2017

How to remove all subviews of a view in Swift?

Following task - remove all subViews of current view. Let's see how we can implement this.

For example we create UIView and add UILabel to it.
var containerView = UIView()
containerView.addSubview(UILabel(frame: CGRect.zero))

1. Simple For Loop
for subView in containerView.subviews {
    subView.removeFromSuperview()
}

2. ForEach Loop
containerView.subviews.forEach {
    $0.removeFromSuperview()
}

3. Using Map Function
containerView.subviews.map { $0.removeFromSuperview() }

4. Making Extension

If we want to make removing enable for all views in project then let's create Extension.
extension UIView {   
    func removeAllSubView() {
        self.subviews.forEach { $0.removeFromSuperview() }
    }
}

containerView.removeAllSubView()

5. Going Universal with Generics

We can go further and make our Extension universal with Generics. Now You can specify which type of subViews You want to remove.
extension UIView {
    
    func removeAllSubViewOfType<T: UIView>(type: T.Type) {
        self.subviews.forEach {
            if ($0 is T) {
                $0.removeFromSuperview()
            }
        }
    }
}

containerView.removeAllSubViewOfType(type: UILabel.self)

6. The Same but Using Filter and Map Functions

The same as above. But here we use chain of High-order functions.
extension UIView {
    
    func removeAllSubViewOfTypeUsingHOF<T: UIView>(type: T.Type) {
        self.subviews.filter({ $0 is T }).map({ $0.removeFromSuperview() })
    }
}

containerView.removeAllSubViewOfTypeUsingHOF(type: UILabel.self)

Thursday, October 19, 2017

Flat nested array recursively in Swift

Following task - make flat array from nested array. Because there are could be any levels of nested array we use recursive approach.

For example - given array [1, [2, [3, 4, 5]]]. We need to get this [1, 2, 3, 4, 5]

Standard Approach

Algorithm
  1. In for loop go through the array
  2. If element of array is int then add it to new array
  3. If element of array is array too then make recursive invoke of function and send this array
We use Any type as type of input array because input array can hold as integers as array. They both are value types, so Any is suitable for us in this function.

Let's get coding.
import UIKit

let array: [Any] = [1, 2, [3]]

func makeFlatArray(_ array: [Any]) -> [Int] {
    var flatArray = [Int]()
    for item in array {
        if let item = item as? Int {
            flatArray.append(item)
        } else if let item = item as? [Any] {
            let result = makeFlatArray(item)
            flatArray += result
        }
    }
    return flatArray
}

print(makeFlatArray([1, 2, 3]))
// [1, 2, 3]
print(makeFlatArray([1, [2, 3, 4]]))
// [1, 2, 3, 4]
print(makeFlatArray([1, [2, [3, 4]]]))
// [1, 2, 3, 4]
print(makeFlatArray([[1], [2, [3, 4, [5]]]]))
// [1, 2, 3, 4, 5]

Using Generics

What if we want to use this function with array of any type. We should use Generics:
func makeFlatArrayGeneric<T>(_ array: [Any]) -> [T] {
    var flatArray = [T]()
    for item in array {
        if let item = item as? T {
            flatArray.append(item)
        } else if let item = item as? [Any] {
            let result: [T] = makeFlatArrayGeneric(item)
            flatArray += result
        }
    }
    return flatArray
}

Now we can use this function with any kind of array. With integer array as previous
let array: [Any] = [1, 2, [3], [4, [5]]]
let items: [Int] = makeFlatArrayGeneric(array)
// [1, 2, 3, 4, 5]

And with array of strings
let array: [Any] = ["A", "BB", ["CCC"], ["DD", ["EE"]]]
let items: [String] = makeFlatArrayGeneric(array)
// ["A", "BB", "CCC", "DD", "EE"]

Make Extension for Array 

What if we want this feature for any array as built in method. Let's create extension for Array Type. Here we use Swift method flatMap.
extension Array {
    
    func makeFlat() -> [Element] {
        let flatArray = self.flatMap { (element) -> [Element] in
            if let array = element as? Array {
                return array.makeFlat()
            }
            return [element]
        }
        return flatArray
    }
}

Result of using array extension.
let array: [Any] = ["A", "BB", ["CCC"], ["DD", ["EE"]]]
print(array.makeFlat())
// ["A", "BB", "CCC", "DD", "EE"]

Tuesday, October 17, 2017

Reverse every even or every odd word in string in swift

Following task - reverse every even or every odd word in sentence.

Algorithm

  1. Get array of words from string (sentence)
  2. Create new empty string
  3. In for loop go through the array and according to condition reverse word or not and append it to new string
Let's get implemented our algorithm.
import UIKit

let str = "This is the string which will be reverted particaually"

enum WhichNumer: Int {
    case Even = 0
    case Odd = 1
}

func reverseWords(str: String, number: WhichNumer = .Even) -> String {
    let array = str.components(separatedBy: " ")
    var newStr = ""
    for i in 0..<array.count {
        if newStr != "" {
            newStr += " "
        }
        let word = array[i]
        if (i + 1) % 2 == number.rawValue {
            newStr += String(word.reversed())
        } else {
            newStr += word
        }
    }
    
    return newStr
}

print(reverseWords(str: str))
// This si the gnirts which lliw be detrever particaually

print(reverseWords(str: str, number: .Odd))
//sihT is eht string hcihw will eb reverted yllauacitrap

But we can improve our code with using High-ordered function. 

There is following algorithm:

1. Create array of string from initial string
str.components(separatedBy: " ")
// ["This", "is", "the", "string", "which", "will", "be", "reverted", "particaually"]

2. Convert this array to enumerated. According to Apple Documentation after this we can get sequence of pairs with index and value.
"Returns a sequence of pairs (n, x), where n represents a consecutive integer starting at zero, and x represents an element of the sequence."
str.components(separatedBy: " ").enumerated()
//    0 : This
//    1 : is
//    2 : the
//    3 : string
//    4 : which
//    5 : will
//    6 : be
//    7 : reverted
//    8 : particaually

3. Now we can use map function to this array of pairs. We check index and modify value if needed.
str.components(separatedBy: " ").enumerated().map { (index, value) -> String in
    if ((index + 1) % 2 == number.rawValue) {
        return String(value.reversed())
    }
    return value
})
// ["This", "si", "the", "gnirts", "which", "lliw", "be", "detrever", "particaually"]

4. Finally, array of words can be convert to string with joined function.
let newStr = str.components(separatedBy: " ").enumerated().map { (index, value) -> String in
    if ((index + 1) % 2 == number.rawValue) {
        return String(value.reversed())
    }
    return value
}.joined(separator: " ")
// This si the gnirts which lliw be detrever particaually

Here new implementation of our function.
func reverseWordsUsingHOF(str: String, number: WhichNumer = .Even) -> String {
    let newStr = str.components(separatedBy: " ").enumerated().map { (index, value) -> String in
        print(index)
        if ((index + 1) % 2 == number.rawValue) {
            return String(value.reversed())
        }
        return value
    }.joined(separator: " ")
    
    return newStr
}

print(reverseWordsUsingHOF(str: str))
// This si the gnirts which lliw be detrever particaually

Thursday, October 12, 2017

iOS code quality. How to write good swift code.

How to write good, clean and understandable code. There are some good practices how to do that. They are simple rules following which you can make your code more quality.


1. Meaningful variable names


Don't create variables and constants with senseless names like in code below. This is bad practice.
var a = 28
var bb = "Aleksei"
var ccc = "IT"

Use meaningful names for variables. This is good practice.
var age = 28
var name = "Aleksei"
var specialisation = "IT"

2. Camel case convention (for filenames and for code)


This is simple one rule. Just use camelCase notation in naming files, variables, classes, functions and etc.
This is bad practice of naming.
var TYPE: String
var Type: String

var COUNTOFUSEDVEHICLES = 0

var countofusedvehicles = 0

class VEHICLESLISTVIEWCONTROLLER: UIViewController {
}

class vehicleslistviewcontroller: UIViewController {
}

This is good practice o naming.
var type: String

var countOfUsedVehicles = 0

class VehiclesListViewController: UIViewController {
}


3. Meaningful data types


Don't create variables with strange data types for variable's name. It can be reason of misunderstood.
This is bad practice.
var type: Int
var count: Double
var price: String

This is good practice. More obviously that count is Integer value.
var type: String
var count: Int
var price: Double

4. Meaningful name for custom classes


Don't create custom classes with senseless names. Later it can be hard to understand what this class is used for. This is bad practice.
class TableViewCell: UITableViewCell {

}

This is good practice. This class is used for displaying vehicle in cell of table.
class VehicleCell: UITableViewCell {
    
}

5. Using constants for storing identifiers


When all identifiers are just string it can be reason of crash after renaming identifier somewhere in code. Because we must change it in all places. We can forget to do it everywhere it is needed.
func configureTableView(){
    self.tableView.register(UINib.init(nibName: "VehicleCell", bundle: nil),
                                forCellReuseIdentifier: "VehicleCell")
    self.tableView.register(UINib.init(nibName: "VehicleHeader", bundle: nil),
                                forHeaderFooterViewReuseIdentifier: "VehicleHeader")
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "VehicleCell", for: indexPath)
}

Move identifiers strings into special constants. This is good practice. Because later we can change identifier string only in one place.
let vehicleCellIdentifier = "VehicleCell"
    
let vehicleHeaderIdentifier = "VehicleHeader"
    
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: vehicleCellIdentifier, for: indexPath)
}

func configureTableView(){
    self.tableView.register(UINib.init(nibName: "VehicleCell", bundle: nil),
                                forCellReuseIdentifier: vehicleCellIdentifier)
    self.tableView.register(UINib.init(nibName: "VehicleHeader", bundle: nil),
                                forHeaderFooterViewReuseIdentifier: vehicleHeaderIdentifier)
}


6. Separate things to different methods


Don't put all things in one method. For example, in code below we configure tableView and also configure navigationItem. It is logically that we can separate this configuration into two functions.

This is bad practice.
override funct viewDidLoad() {
    super.viewDidLoad()
    self.tableView.tableFooterView = UIView()
    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.estimatedRowHeight = 200.0
    self.tableView.register(UINib.init(nibName: "VehicleCell", bundle: nil),
                                forCellReuseIdentifier: "VehicleCell")

    let backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
    self.navigationItem.backBarButtonItem = backBarButtonItem
        
    let favoritesImage = UIImage(named: "ic_favorite_48pt")
    let favoritesButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    favoritesButton.addTarget(self, action: #selector(favoritesButtonTapped), for: .touchUpInside)
    favoritesButton.setImage(favoritesImage, for: .normal)
    let favoritesBarButton = UIBarButtonItem(customView: favoritesButton)
    self.navigationItem.rightBarButtonItem = favoritesBarButton
}


Here we separate configuration functions. This is good practice.
override func viewDidLoad() {
     super.viewDidLoad()
     self.configureNavBar()
     self.configureTableView()
}
    
func configureTableView() {
    self.tableView.tableFooterView = UIView()
    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.estimatedRowHeight = 200.0
    self.tableView.register(UINib.init(nibName: "VehicleCell", bundle: nil),
                                forCellReuseIdentifier: "VehicleCell")
}
    
func configureNavBar() {
    let backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: self, action: nil)
    self.navigationItem.backBarButtonItem = backBarButtonItem
        
    let favoritesImage = UIImage(named: "ic_favorite_48pt")
    let favoritesButton = UIButton(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
    favoritesButton.addTarget(self, action: #selector(favoritesButtonTapped), for: .touchUpInside)
    favoritesButton.setImage(favoritesImage, for: .normal)
    let favoritesBarButton = UIBarButtonItem(customView: favoritesButton)
    self.navigationItem.rightBarButtonItem = favoritesBarButton
}

7. Do not print useless information to console. 


It is simple. Just do not put useless print statements. Because it can be hard to find useful console log.
print("It works!!!")

8. Curly braces and new lines


When using curly braces is bad practice to move opening curly brace to new line.

Bad practice in function.
func configureTableView() 
{
    self.tableView.tableFooterView = UIView()
    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.estimatedRowHeight = 200.0
    self.tableView.register(UINib.init(nibName: "VehicleCell", bundle: nil),
                                forCellReuseIdentifier: "VehicleCell")
}

It is good practice to leave opening curly brace on the same line.
func configureTableView() {
    self.tableView.tableFooterView = UIView()
    self.tableView.rowHeight = UITableViewAutomaticDimension
    self.tableView.estimatedRowHeight = 200.0
    self.tableView.register(UINib.init(nibName: "VehicleCell", bundle: nil),
                                forCellReuseIdentifier: "VehicleCell")
}

The same rule for "if condition" operator. This is bad practice.
let a = 10
let b = 20
if (b > a)
{
    print("This is bad code style")
}

This is good practice.
let a = 10
let b = 20
if (b > a) {
    print("This is good code style")
}