DynamicFontSize for custom fonts in Swift


Hi Friends,
Set your custom fonts with dynamic font size.

Screenshot 2020-02-07 at 11.23.56 PM

extension UIFont {
    
    /// CustomFont
    /// - Parameter style: UIFont.TextStyle
    static func customFont(style textStyle: UIFont.TextStyle) -> UIFont {
        let fontName = "Arial"
        let fontDescripter = UIFontDescriptor.preferredFontDescriptor(withTextStyle: textStyle)
        
        guard let customFont = UIFont(name: fontName, size: fontDescripter.pointSize) else {
            fatalError("failed to load the \(fontName) font.")
        }
        
        return UIFontMetrics.default.scaledFont(for: customFont)
    }
}

You can use this dynamic fonts like below

        title1Label.font = UIFont.customFont(style: .title1)
        title2Label.font = UIFont.customFont(style: .title2)
        title3Label.font = UIFont.customFont(style: .title3)
        largeTitleLabel.font = UIFont.customFont(style: .largeTitle)
        bodyLabel.font = UIFont.customFont(style: .body)
        caption2Label.font = UIFont.customFont(style: .caption2)
        caption1Label.font = UIFont.customFont(style: .caption1)
        footnoteLabel.font = UIFont.customFont(style: .footnote)
        headlineLabel.font = UIFont.customFont(style: .headline)
        subHeadLabel.font = UIFont.customFont(style: .subheadline)
        calloutLabel.font = UIFont.customFont(style: .callout)

adjustsFontForContentSizeCategory is automatically updates its font when the device’s content size category changes.

title1Label.adjustsFontForContentSizeCategory = true

– How to make an iOS App
Kathiresan Murugan

PDFView in Swift


Hi Friends,

PDFKit framework is available in iOS 11.0* and macOS 10.4*
Implement few lines of code to view your pdf document in you ViewController.

import PDFKit

Implement in UIViewController.viewDidLoad()

        let pdfView = PDFView(frame: view.bounds)
        pdfView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        view.addSubview(pdfView)
        
        pdfView.autoScales = true
        
        let filePath = Bundle.main.url(forResource: "Sample", withExtension: "pdf")
        pdfView.document = PDFDocument(url: filePath!)
Simulator Screen Shot - iPhone Xʀ - 2020-01-23 at 15.15.07
Sample PDFView snapshot

– How to make an iOS App
Kathiresan Murugan

Protocol Oriented programming in Swift


Hi Friends,

One of the powerful concept called Protocol Oriented Programming (POP) was introduced in WWDC 2015

Here I have some eg. for understanding POP

Basically we use protocols to implement delegation. But now protocols will split a logics from class, structures and enums.

struct People {
    var fatherName: String

    var name: String

    var age: Int
}

Here I create People structure. Its contains name, age properties.

Declaring Protocol

/// Report protocol
protocol Report {
    
    var fullName: String { get }
    
    func textualDescription()
    
    func myAge() -> Int
}

Here I create a protocol named Report contains variable with get and set (read and write) permission.

functions with return types.

Notes: let is not allowed in protocols.

/// Extending people struct. conforming Report protocol
extension People: Report {
    var fullName: String {
        get {
            return name + " " + fatherName
        }
    }
    
    func textualDescription() {
        print("Father's name: \(fatherName), Name: \(name), Age: \(age)")
    }
    
    func myAge() -> Int {
        age
    }
}

Here I extend people struct with conforming Report protocol. and added protocols stubs.

// Implementation
let people = People(fatherName: "Murugan", name: "Kathiresan", age: 27)
people.fullName 
//Kathiresan Murugan

people.textualDescription() 
//Father's name: Murugan, Name: Kathiresan, Age: 27

people.myAge() 
//27

Protocol Composition

protocol Named {
    var name: String { get }
}
protocol Aged {
    var age: Int { get }
}

Here I created two protocols Named and Aged.

struct Person: Named, Aged {
    var name: String
    var age: Int
}

Person structure conformed with Named and Aged protocols.

Implementation

func wishHappyBirthday(to celebrator: Named & Aged) {
    print("Happy birthday, \(celebrator.name), you're \(celebrator.age)!")
}

let birthdayPerson = Person(name: "Kathiresan", age: 27)
wishHappyBirthday(to: birthdayPerson)
//Happy birthday, Kathiresan, you're 27!

Another eg. with class

class Location {
    var latitude: Double
    var longitude: Double
    init(latitude: Double, longitude: Double) {
        self.latitude = latitude
        self.longitude = longitude
    }
}
class City: Location, Named {
    var name: String
    init(name: String, latitude: Double, longitude: Double) {
        self.name = name
        super.init(latitude: latitude, longitude: longitude)
    }
}

Implementation

func beginConcert(in location: Location & Named) {
    print("Hello, \(location.name)!")
}

let seattle = City(name: "Seattle", latitude: 47.6, longitude: -122.3)
beginConcert(in: seattle)
// Prints "Hello, Seattle!"

 
Try POP in your project and optimise your code.

– How to make an iOS App
Kathiresan Murugan

Easy TextField Validation in Swift5


Hi Friends,

I have a easy logic to validate a textFields easily.

for eg. I have implemented a email validation for this textfield.

/// Validate type
enum ValidateType {
    case email
}

Validation properties with User experience.

extension ValidateType {
    
    /// Validation
    /// - Parameter text: text
    func isValid(text: String?) -> ValidationResult {
      guard let text = text else { return .init(isSuccess: false, error: "can't be empty") }

      switch self {
      case .email: return text.isEmail
      }

    }

    /// Keyboard type
    func keyboardType() -> UIKeyboardType {
        switch self {
        case .email: return .emailAddress
        }
    }

    /// Text content type
    func textContentType() -> UITextContentType {
        switch self {
        case .email: return .emailAddress
        }
    }
}

Validation Result is really help to validate a textFields

/// Validation result
struct ValidationResult {
    
    /// is Success Bool
    var isSuccess: Bool
    
    /// Error description default nil
    var error: String?
    
    /// Init
    /// - Parameters:
    ///   - isSuccess: success bool. default true
    ///   - debug: debug string. default nil
    init(isSuccess: Bool = true, error description: String? = nil) {
        self.isSuccess = isSuccess
        self.error = description
    }
}

String Validation. check my

post String Validation using Swift3

/// String Validation
extension String {

    /// Is not blank
    var isNotBlank: ValidationResult {
        if self.trimmingCharacters(in: .whitespaces).isEmpty {
            return .init(isSuccess: false, error: "Can't empty")
        } else {
            return .init()
        }
    }

    /// Trimmed string
    var trimmedString: String {
        self.trimmingCharacters(in: .whitespacesAndNewlines)
    }

    /// Email string is valid
    var isEmail: ValidationResult {
        
        let notBlankResult = self.isNotBlank
        
        if notBlankResult.isSuccess {
            
            let actualText = self.trimmedString
            
            let emailRegEx = "^[a-zA-Z0-9_+&*-]+(?:\\." + "[a-zA-Z0-9_+&*-]+)*@" + "(?:[a-zA-Z0-9-]+\\.)+[a-z" + "A-Z]{2,7}$"
            //"[A-Z0-9a-z._%+-]+@[A-Za-z0-9-]+\\.[A-Za-z]{2,}"
            let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
            
            if emailTest.evaluate(with: actualText) {
                return ValidationResult()
            } else {
                return ValidationResult(isSuccess: false, error: "Not in email format")
            }
        } else {
            return notBlankResult
        }
    }
    
}

Eg. Custom textField class
You can use textField with ValideType. It will help easy validate your forms

/// Custom textField with Validation type
class customTextField: UITextField {

    /// Validate type. default .none
    var validateType: ValidateType = .none

    /// Optional field. default false
    var isOptional: Bool = false

    /// Is valid text
    func isValid() -> ValidationResult {
        return validateType.isValid(text: text)
    }
}

Implementation. In ViewController.swift

/// Is Valid fields are valid
func isValidateForm() -> Bool {

 if !emailTextField.isValid() {
  // Show error alert
  return false
 }
 return true
}

– How to make an iOS App
Kathiresan Murugan

Use Any datatype for struct property in swift


Hi Friends,

Here I have implemented a sample code to implement Model class. Property may be String or Int. So, that I set it as Any.

struct MyStruct: Decodable {
    let anyProperty: Any
    
    enum CodingKeys: String, CodingKey {
        case anyProperty
    }
    
    init(from decoder: Decoder) throws {
        do {
            let container = try decoder.container(keyedBy: CodingKeys.self)
            if let stringProperty = try? container.decode(String.self, forKey: .anyProperty) {
                anyProperty = stringProperty
            } else if let intProperty = try? container.decode(Int.self, forKey: .anyProperty) {
                anyProperty = intProperty
            } else {
                throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: container.codingPath, debugDescription: "Not a JSON"))
            }
        }
    }
    
}

– How to make an iOS App
Kathiresan Murugan

Disable Dark mode in iOS 13 for your app


Hi Friends,

Basically iOS 13 application UI appearance will automatically support dark mode.

Basically some of the application didn’t need dark mode support so, They will start searching how to disable dark mode in my application?

We can handle for a particular viewController

In ViewDidLoad()

overrideUserInterfaceStyle = .light

check for overrideUserinterface

check for developer.apple/…/interfaceStyle

Or else you can disable for hole application by adding UIUserInterfaceStyle as Light in info.plist

key = UIUserInterfaceStyle
value = Light

– How to make an iOS App
ktrkathir

Captcha Generator Swift Package


Hi Friends,

As per comment of captcha Objective-CScreenshot 2019-12-15 at 9.40.26 AM

Screenshot 2019-12-15 at 9.53.39 AM
Captcha generator swift

SwiftPackage Source code GitHub

Implementation

  /// Captcha generator
  var captcha = CaptchaGenerator()
  captchaLabel.attributedText = captcha.generate()
/// Validation
 if captcha.isMatched(text: field.text ?? "") {
   // success
 }

– How to make an iOS App
ktrkathir

MediaPicker Swift Package


Hi Friends,

Here I posted MediaPicker Swift Package. Its contains a Custom ImagePicker and Image storing in document directory.

You can download this swift package from GitHub.com

example code to pick a image form take photo, camera roll and gallery.

ImagePicker

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        //ImagePicker example code
        let imagePicker = ImagePicker(presentationController: self, delegate: self)
        imagePicker.present(from: self.view)
}
extension ViewController: ImagePickerDelegate {
    
    func imagePicker(picker: ImagePicker, didSelected image: UIImage?, apikey key: String?) {
        guard let image = image else { return }
        // write your code here...
    }
    
    
}

 


MediaManager – Download image from url and store to document directory

// Media manager example code
        let imageURL = URL(string: "http://mediastore.com/public/avatar/134356300.jpeg")!
        MediaManager.shared.downloadImage(url: imageURL, completion: { (image) in
            guard let image = image else { return }
            // write your code here...

        }) { (errorLog) in
            guard let errorLog = errorLog else { return }
            
            print(errorLog)
        }

MediaManager – Download image from url and show in UIImageView

 // MediaManager + UIImageView
        let bannerURLString = "http://mediastore.com/public/banner/001.jpeg"
        UIImageView().imageFromURL(urlString: bannerURLString)

– How to make an iOS App
ktrkathir

HttpConnection Swift Package


Hi Friends,

Here I posted my first swift package in Swift5.1.
Purpose of this package is helps to retrieve data from url.

You can download this swift package from GitHub.com

example code to retrieve personal detail from url.

Modelclass for personal detail

import HttpConnection

/// Personal detail
struct PersonalDetail: Decodable {
    let name: String
    let age: Int
    let dob: String
    let address: String
}

Extens for api calling

extension PersonalDetail {
    
    /// Fetch from url
    /// - Parameter result: Personal detail
    static func fetch(result: @escaping((Result) -> Void)) {
        
        let urlString = "http://enterpriseManage.com/db/v1/personal_detail"
        // create URL
        guard let url = URL(string: urlString) else {
            result(.failure(.invalidURL))
            return
        }
        // Create URLInputs using url.
        let urlInput: URLInputs = .init(requestURL: url)
        
        fetchResource(urlInputs: urlInput, completion: result)
    }
}

– How to make an iOS App
ktrkathir

Starter, show at first time launching your app


Hi Friends,

Here I developed a feature list viewController like Apple native apps.
Most of the apple native apps was showing major features list at first time of application opened. Its simple, clear designed.

So, I just develop like a feature list screen. I will call this the “Starter

Starter is used to show major 3 features at center of the screen.

StarterViewController

I have created a GitHub Repository for Starter. You can easily download here

Drag and drop Get Start folder and implement in AppDelegate didFinishLaunchingWithOptions

 /// Show starter
        let startVC = StarterViewController.loadFromNib()
        startVC.loadView()
        startVC.themeColor = UIColor.blue.withAlphaComponent(0.7)
        startVC.welcomeLabel.text = "Welcome to"
        startVC.appNameLabel.text = "Starter"
        startVC.featureDescriptionLabel.text = "You can use starter show release notes better and clearly like Apple native apps."
        startVC.dismiss.setTitle("Continue", for: .normal)
        
        let details = [FeatureDetail(icon: #imageLiteral(resourceName: "photos"),
                                     title: "Clear details",
                                     subTitle: "Present a major features to yours like this."),
                       FeatureDetail(icon: #imageLiteral(resourceName: "photos"),
                                     title: "Fully Customized",
                                     subTitle: "Full permission to customise what you need."),
                       FeatureDetail(icon: #imageLiteral(resourceName: "photos"),
                                     title: "Press continue",
                                     subTitle: "Press continue button below of this to start using your application.")]
        startVC.features = details
        startVC.delegate = self
        window?.rootViewController = startVC
    

protocol implementation

/// MARK: Starter View Delegate
extension AppDelegate: StarterViewDelegate {
    
    func continueButtonWasTapped(startViewController: StarterViewController) {
        // StarterViewController continue button was tapped.
        
        let initialVC = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateInitialViewController()
        window?.rootViewController = initialVC
    }
    
}

How to make an iOS App
– ktrkathir

“Finding Emojis in String😀” using Swift


Hi Friends,

Emoji detection is very Important in Chat application.

After I done chat conversation screen and I saw a WhatsApp application and I find a Emoji dictation That will show little bit larger than text. So, I analyse how they are finding the emoji in string?.

Finally I found the solution for this.

Using CoreText Framework, UnicodeScalar in Foundation

import Foundation
import CoreText

extension UnicodeScalar {
    /// Note: This method is part of Swift 5, so you can omit this.
    /// See: https://developer.apple.com/documentation/swift/unicode/scalar
    var isEmoji: Bool {
        switch value {
        case 0x1F600...0x1F64F, // Emotions
        0x1F300...0x1F5FF, // Misc Symbols and Pictographs
        0x1F680...0x1F6FF, // Transport and Map
        0x1F1E6...0x1F1FF, // Regional country flags
        0x2600...0x26FF, // Misc symbols
        0x2700...0x27BF, // Dingbats
        0xE0020...0xE007F, // Tags
        0xFE00...0xFE0F, // Variation Selectors
        0x1F900...0x1F9FF, // Supplemental Symbols and Pictographs
        0x1F018...0x1F270, // Various asian characters
        0x238C...0x2454, // Misc items
        0x20D0...0x20FF: // Combining Diacritical Marks for Symbols
            return true
            
        default: return false
        }
    }
    
    var isZeroWidthJoiner: Bool {
        return value == 8205
    }
}

In String Extension class

extension String {
    
    // Not needed anymore in swift 4.2 and later, using `.count` will give you the correct result
    var glyphCount: Int {
        let richText = NSAttributedString(string: self)
        let line = CTLineCreateWithAttributedString(richText)
        return CTLineGetGlyphCount(line)
    }
    
    var isSingleEmoji: Bool {
        return glyphCount == 1 && containsEmoji
    }
    
    var containsEmoji: Bool {
        return unicodeScalars.contains { $0.isEmoji }
    }
    
    var containsOnlyEmoji: Bool {
        return !isEmpty
            && !unicodeScalars.contains(where: {
                !$0.isEmoji && !$0.isZeroWidthJoiner
            })
    }
    
    // The next tricks are mostly to demonstrate how tricky it can be to determine emoji's
    // If anyone has suggestions how to improve this, please let me know
    var emojiString: String {
        return emojiScalars.map { String($0) }.reduce("", +)
    }
    
    var emojis: [String] {
        var scalars: [[UnicodeScalar]] = []
        var currentScalarSet: [UnicodeScalar] = []
        var previousScalar: UnicodeScalar?
        
        for scalar in emojiScalars {
            if let prev = previousScalar, !prev.isZeroWidthJoiner, !scalar.isZeroWidthJoiner {
                scalars.append(currentScalarSet)
                currentScalarSet = []
            }
            currentScalarSet.append(scalar)
            
            previousScalar = scalar
        }
        
        scalars.append(currentScalarSet)
        
        return scalars.map { $0.map { String($0) }.reduce("", +) }
    }
    
    fileprivate var emojiScalars: [UnicodeScalar] {
        var chars: [UnicodeScalar] = []
        var previous: UnicodeScalar?
        for cur in unicodeScalars {
            if let previous = previous, previous.isZeroWidthJoiner, cur.isEmoji {
                chars.append(previous)
                chars.append(cur)
                
            } else if cur.isEmoji {
                chars.append(cur)
            }
            
            previous = cur
        }
        
        return chars
    }
}

Here I unit test emojis

  func testEmojo() {
        
        XCTAssertTrue("😀".isSingleEmoji)
        XCTAssertTrue("👋🏽🏛".containsOnlyEmoji)
        XCTAssertTrue("Hello 👨‍👩‍👧‍👧".containsEmoji)
        
        XCTAssertFalse("a".isSingleEmoji)
        XCTAssertFalse("🙀1😈".containsOnlyEmoji)
        XCTAssertFalse("Hello world".containsEmoji)
        
        XCTAssertEqual("🙀5🎃".emojis, ["🙀","🎃"])
        XCTAssertEqual("👣1🙏🏽".emojiString, "👣🙏🏽")
        XCTAssertEqual("👨".glyphCount, 1)
        XCTAssertEqual("👨‍👨‍👧🤳".glyphCount, 2)

        XCTAssertEqual("🐽".count, 1)
        XCTAssertEqual("🦊🥛".count, 2)
        
        XCTAssertNotEqual("🛴1🚘".emojis, ["🛴"])
        XCTAssertNotEqual("🚄asdf🚜".emojiString, "🚄asdf🚜")
        XCTAssertNotEqual("🗽US🌂".emojiString, "🗽US")
        XCTAssertNotEqual("🗽US🌂".emojiString, "US🌂")
    }

– How to make an iOS App
ktrkathir

Reusable UITableViewDataSource in Swift


Hi Friends,

After long time I have prepare a post for my blog. In every application we are using UITableView. We will declare UITableViewDataSource for every TableView separately. So, implement a Generic TableViewDataSource like below.

Reusable UITableViewDataSource is very easy to implement and its totally generic UITableViewDataSource.

The Data

make DataSource reusable and easily modified, we’ll create an enum which will represent the data for a single cell in our app.

enum CellType {
    case Switch(text: String)
    case Segue(text: String)
    case info(text: String, detail: String)
    
    var identifer: String {
        switch self {
        case .Switch: return "switchCell"
        case .Segue: return "segueCell"
        case .info: return "infoCell"
    }
    }
}

This has everything our datasource would need, including the cell-reuse identifiers

Also create a struct to represent a section in out TableView

struct ListSection {
    var title: String?
    var cellData: [CellType]
    
    init(title: String?, cellData: [CellType]) {
        self.title = title
        self.cellData = cellData
    }
}

SourceDataSource

Now that we have clear value types that represent our data, we can create our actual data source. It only need to have one property we’ll call sections,

class SourceDataSource: NSObject {

    var source: [ListSection]
    
    init(section source: [ListSection]) {
        self.source = source
    }
}

as well as implement the UITableViewDataSource protocol and required protocol methods.

extension SourceDataSource: UITableViewDataSource {

   func numberOfSections(in tableView: UITableView) -> Int {
        return source.count
    }

   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return source[section].cellData.count
    }

   func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
        return source[section].title
    }
}

As well as implement CellforRowAt in SourceDataSource

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cellData = source[indexPath.section].cellData[indexPath.row]
        
        if let cell = tableView.dequeueReusableCell(withIdentifier: cellData.identifer) {
            switch cellData {
            case .Switch(let text):
                cell.textLabel?.text = text
                cell.accessoryType = .detailButton
                cell.accessoryView = UISwitch()
                
            case .Segue(let text):
                cell.textLabel?.text = text
                cell.accessoryType = .disclosureIndicator

            case .info(let text, let detail):
                cell.textLabel?.text = text
                cell.detailTextLabel?.text = detail
            }
            return cell
        } else {
            fatalError("Unknown identifier")
        }
    }

The Model

Create a model value with in actual ViewController class.

struct Model {
    static let data = [
        ListSection(title: "General",
                    cellData: [CellType.Switch(text: "Network"),
                               CellType.Segue(text: "Profile")]),
        ListSection(title: "Stats",
                    cellData: [CellType.info(text: "Usage", detail: "2 days")])
    ]
}

Here I have used Interface builder, So, I’ve added a UITableView in UIViewController and added necessary prototype cells with correct cell identifer for our ListSection.

Prototype cells

In actual ViewController code

class MyList: UIViewController {
    
    @IBOutlet weak var tableView: UITableView!
    
    let dataSource = SourceDataSource(section: Model.data)
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.dataSource = dataSource
    }
}

Now we get a output like below

Custom Datasource output

Try this logic in your application and enjoy the experience

– How to make an iOS App
ktrkathir

3D Touch – Home screen quick actions dynamically in Swift


Hello Friends,

Here I have implemented a dynamic Home screen Quick action – shortcutItems

Home screen QuickActions

In this tutorial I have created 3 shortcuts to access a TabBarController screens.

  • Dashboard
  • Health
  • Games

UIApplicationShortcutItem contains

  • Type
  • localizedTitle
  • localizedSubtitle
  • icon and UserInfo
let dashboard = UIApplicationShortcutItem(type: "Screen1", localizedTitle: "Dashboard", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: "dashboard"), userInfo: nil) // shortcut 1
        
let health = UIApplicationShortcutItem(type: "Screen2", localizedTitle: "Health", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: "Health"), userInfo: nil) // shortcut 2
        
let games = UIApplicationShortcutItem(type: "Screen3", localizedTitle: "Games", localizedSubtitle: nil, icon: UIApplicationShortcutIcon(templateImageName: "Games"), userInfo: nil)
// shortcut 3
 
UIApplication.shared.shortcutItems = [dashboard, health, games] // Assigning all shortcuts

Handle user tapped shortcut item in AppDelegate.

   func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
        
       if let tabController = window?.rootViewController as? UITabBarController {
            switch shortcutItem.type {
            case "Screen1":
                tabController.selectedIndex = 0
            case "Screen2":
            tabController.selectedIndex = 1
            default:
                tabController.selectedIndex = 2
            }
        }
        completionHandler(true)
    }

– How to make an iOS App
ktrkathir

Dynamic App icon in iOS 10.3 and above


Hi Friends,

iOS 10.3 Apple gives ability to change App icon by programmatically. Its powerfull. But, You can’t able to update like clock app.

Dynamic AppIcon
Simulator screenshot

AppIcons pixel size.

      • 2x.png = 120×120
      • 3x.png = 180×180

Resource files

      • stack2x.png
      • stack3x.png
      • victory2x.png
      • victory3x.png
      • world2x.png
      • world3x.png

Follow 3 steps to archive dynamic app icon in iOS

      1. Drag and drop AppIcon 2x and 3x images to project
      2. Register AppIcons in info.plist using CFBundleIcons
      3. Set AppIcon dynamically using setAlternateIconName

Lets start.

Step 1:  Drag and drop AppIcon images is project navigator. Dynamic AppIcon - Project navigation

Step 2:  Use CFBundleIcons in info.plist. Use three dictionary keys to register primary icon and Alternate icons.

      • Primaty icon – CFBundlePrimaryIcon
      • Alternate icon – CFBundleAlternateIcons

Dynamic AppIcon info.plist

Step 3: Use setAlternateIconName method and set update registered AppIcon.

As I mentioned at top of the post. (image: Simulator screenshot)

I have designed there UIButton and set AppIcon images for that. In ViewController.swift I have created a three UIButton Actions and additional method to update AppIcon.

Check Alternate AppIcon is supported this is app. Using UIApplication.shared.supportsAlternateIcons

Update Alternate AppIcon using UIApplication.shared.setAlternateIconName

    @IBAction func icon1(_ sender: Any) {
        setIcon(iconName: "AppIcon-1")
    }
    
    @IBAction func icon2(_ sender: Any) {
        setIcon(iconName: "AppIcon-2")
    }
    
    @IBAction func icon3(_ sender: Any) {
        setIcon(iconName: "AppIcon-3")
    }
    
    func setIcon(iconName: String) {
        
        guard UIApplication.shared.supportsAlternateIcons else {
            return
        }
        
        UIApplication.shared.setAlternateIconName(iconName) { (error) in
            if let error = error {
                print("Error: \(error)")
            } else {
                print("App icon updated.")
            }
        }
    }

That all. Done it.

Notes:

To reset AppIcon to primary. Set AlternateIcon name as nil.

UIApplication.shared.setAlternateIconName(nil)

Source code: download

– How to make an iOS App
ktr kathir

Design a Bus | Theatre tickets booking screen UI in Swift


Hi Friends,

I have achieved a design of Bus tickets booking screen UI on Swift.
Yes.

How did this?
I used CAShapeLayer.

SeatShapeLayer
Bus ticket UI

Here I have created a subclass for CAShapeLayer as SeatShapeLayer.

/// Seat shape layer
class SeatShapeLayer: CAShapeLayer {
    
    override init(layer: Any) {
        super.init(layer: layer)
    }
    
    fileprivate var size: CGSize!
    
    init(frame: CGRect) {
        super.init()
        self.frame = frame
        size = frame.size
        setup()
    }
    
    override init() {
        super.init()
        setup()
    }
    
    /// Setup
    func setup() {
        strokeColor = UIColor.lightGray.cgColor
        fillColor = UIColor.clear.cgColor
        
        let drawPath = CGMutablePath()
        drawPath.addRoundedRect(in: CGRect(x: 0, y: 0, width: size.width, height: size.height), cornerWidth: 4, cornerHeight: 4, transform: .identity)
        path = drawPath
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    /// Selected
    func selected() {
            let textLayer = CATextLayer()
            textLayer.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            textLayer.alignmentMode = .center
            textLayer.fontSize = 15
            textLayer.cornerRadius = 4
            textLayer.backgroundColor = UIColor.lightGray.cgColor
            textLayer.foregroundColor = UIColor.white.cgColor
            addSublayer(textLayer)
    }
}

In your viewController. You can call SeatShapeLayer.

//In viewDidLoad
 var x = 10
        var y = 100
        
        for _ in 0...10 {
            for i in 0...2 {
                let seatLayer = SeatShapeLayer(frame: CGRect(x: x, y: y, width: 20, height: 20))
                view.layer.addSublayer(seatLayer)
                x = x + 20 + 5
                if i % 2 == 0 {
                    x = x + 10
                }
            }
            x = 10
          y = y + 20 + 5
        }

Use touches ended to track if the seat was clicked.

 override func touchesEnded(_ touches: Set, with event: UIEvent?) {
        if let touch = touches.first {
            let point = touch.location(in: self.view)
            
            if let layer = self.view.layer.hitTest(point) as? SeatShapeLayer {
                layer.selected()
            } else if  let layer = self.view.layer.hitTest(point) as? CATextLayer {
               layer.removeFromSuperlayer()
            }
        }
    }

– How to make an iOS App
ktrkathir

Draw shapes using CAShapeLayer iOS


Hi Friends,

Using CAShapeLayer you can crop your UIImageView with any shapes. Here I done a small example like below.

Layer crop

let shapeLayer = CAShapeLayer()
        shapeLayer.strokeColor = UIColor.black.cgColor
        shapeLayer.fillColor = UIColor.blue.cgColor
        shapeLayer.lineWidth = 2
        
        let path = CGMutablePath()
        path.addEllipse(in: CGRect(x: 0, y: 0, width: 100, height: 100))
        path.move(to: .zero)
        path.addLine(to: CGPoint(x: 0, y: 50))
        path.addQuadCurve(to: CGPoint(x: 50, y: 0), control: CGPoint(x: 7, y: 7))
        
        shapeLayer.path = path
        imageView.layer.mask = shapeLayer

– How to make an iOS App
ktrkathir

Convert String to Image using UIGraphics


Hi Friends,

Its Simple to convert a String to image by using UIGraphics. Here I have shared a code. This is a extension function of String. It will return a Image.

// MARK: - String Extension functions.
extension String {
    
    /// Convert String to Image
    ///
    /// - Returns: image.
    func image() -> UIImage? {
        // Size of Image
        let size = CGSize(width: 100, height: 100)
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        UIColor.white.set() //clear.set()
        
        let rect = CGRect(origin: CGPoint(), size: size)
        UIRectFill(CGRect(origin: CGPoint(), size: size))
        (self as NSString).draw(in: rect, withAttributes: [NSAttributedString.Key.font: UIFont.systemFont(ofSize: 90)])
        
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
}

– How to make an iOS App
ktrkathir

Location based Augmented Reality using ARKit in iOS


Hi Friends,

Its time to learn ARKit in iOS. Yes. I have start learning of ARKit in iOS.

Scope: Showing information for particular location coordinates. Like below image

Location based AR

Using ARKit and CoreLocation Framework‘s. Its possible to archive.

I have set of places like

 var places: [Place] = [Place(name: "L", lati: 11.053791, lngi: 76.990920, id: 1),Place(name: "R", lati: 11.051854, lngi: 76.991360, id: 2),Place(name: "F", lati: 11.052917, lngi: 76.990507, id: 3),Place(name: "B", lati: 11.053418, lngi: 76.992725, id: 4)]

What I done this is project is.

    1. I have used above static places and converted to SCNNode(SceneNode).
    2. Placing each SCNNode in position of location coordinates. Have to convert coordinates to XYZ Axis.
    3. Based on Z axis have to scale a SCNNode. Then only It will show big when user reach near to the place.
    4. While user rotate iPhone. SCNNode will automatically rotate by using transformMatrix.
    5. When SCNNode is visible. Automatically Particular position information will be show on the top of the screen.

For your Understanding Here I added this image how Scene kit axis are.
Scene kit Axis

Source code: GitHub

– How to make an iOS App
ktrkathir

Custom DatePickerViewController in Swift


Preview screenshot
Custom DatepickerViewController

Call this Class like below

let picker = CustomDatePickerViewController(title: "Schedule", from: Date())
        picker.okButtonSelected { (selectedDate) in
            print(selectedDate.time)
            print(selectedDate.day)
        }
        
        DispatchQueue.main.async {
            self.present(picker, animated: true, completion: nil)
        }

Download complete source code: Custom DatePickerViewController


– How to make an iOS App
ktrkathir

Check your network connection using Network.framework in iOS 12.0 and above.


HI Developer,

When ever we are calling url on iOS. Before we will check is we are connected to network or not.
Many ways in iOS to detect a network connection state. Here I have tried. by Network.Framework

Class for Checking reachability connection

import Network

/// Network connection
class NetworkConnection {
    
    /// Dispatch queue
   private var queue = DispatchQueue(label: "Monitor", qos: .default, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil)
    
    /// Network connection monitor. It will automatically notify when ever you connection was update.
    ///
    /// - Parameter isConnected: isConnected to internet or not.
    func networkMonitor(isConnected: @escaping((_ state: Bool,_ interfare: String?) -> ())) {
        
        let pathMonitor = NWPathMonitor(requiredInterfaceType: .wifi)
        
        pathMonitor.pathUpdateHandler = { path in
            
            if path.status == NWPath.Status.satisfied {
                
                if path.usesInterfaceType(.wifi) {
                    isConnected(true, "WiFi")
                } else if path.usesInterfaceType(.cellular) {
                    isConnected(true, "cellular")
                } else if path.usesInterfaceType(.wiredEthernet) {
                    isConnected(true, "wiredEthernet")
                } else {
                    isConnected(true, "others")
                }
            } else {
                isConnected(false, nil)
            }
            print("is Cellular data: \(path.isExpensive)") //Checking is this is a Cellular data
        }
        pathMonitor.start(queue: queue)
    }
}

On your ViewController.swift

        //Handle your network updations
        let networkConnection = NetworkConnection()
        networkConnection.networkMonitor { (isConnected, connection) in
            if isConnected {
                let mainQueue = DispatchQueue.main
                mainQueue.async {
                    self.view.backgroundColor = UIColor.green.withAlphaComponent(0.9)
                    self.title = "Network connected to \(connection!)"
                }
            } else {
                let mainQueue = DispatchQueue.main
                mainQueue.async {
                    self.view.backgroundColor = UIColor.orange.withAlphaComponent(0.8)
                    self.title = "Network not connected"
                }
            }
        }

GitHub link – NetworkChecker

– How to make an iOS App
ktrkathir