Skip to main content

Posts

Showing posts with the label Theory

Swift Generics Explained – A Practical Guide

If you've written Swift for even a short time, you've already used Generics —whether you realized it or not. Types like Array , Dictionary , Set , and even Optional are all built using generics. Generics are one of Swift's most powerful language features because they help us write reusable, type-safe, and maintainable code . Let's understand them step by step. Why Do We Need Generics? Imagine writing separate functions for every data type. func printInt(_ value: Int) { ... } func printString(_ value: String) { ... } func printDouble(_ value: Double) { ... } The logic is identical, but we're repeating code simply because the data types are different. One option is to use Any . func printValue(_ value: Any) { print(value) } While this works, it comes with a drawback—you lose compile-time type safety and often need runtime type casting ( as? or as! ). Generics solve this problem by allowing us to write code once and reuse it with different data types without sacr...

♻️ Reusing Image with Template render mode in iOS

UIImage comes with property " renderingMode " from iOS 7 onwards. It can be set either 'alwaysTemplate' or 'alwaysOriginal'. This enum property helps us to re-use images that may thin your app size too. Let's get into to a real scenario ! I have added button as heart icon that gives like or dislike functionality for a picture. As you can see in the result below, heart image turns red when liked and stays gray when disliked. In such cases only one image asset can be used. Considering a UIButton object already created and added as a subview in the project, let's start with functionality. Again, I have only one image with name 'heart' in the asset folder (with gray fill). Using same image, I can create 2 instances of UIImage objects using rendering modes.     let notLikedImage = UIImage . init (named: "heart" )?. withRenderingMode (. alwaysOriginal )  let likedImage = UIImage . init (named: "heart" )?....

UICollectionViewCell shows with wrong size on First time - Solved

We commonly use Collection view where its cell size calculated run time. The flow layout delegate is responsible to return individual cell sizes. BUT in most of the cases, delegate method `collectionView: layout sizeForItem:` expects cell size too early. Before generating actual cell size. extension YourViewController : UICollectionViewDelegateFlowLayout { func collectionView ( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize (width: externalWidth, height: externalHeight) } } For instance, if a cell size depends on external view and its frame is not yet ready - results with wrong (or outdated) cell size. Typically happens for the first time view controller laid out all views. You can find similar queries in StackOverflow community : Collection view sizeForItemNotWorking UICollectionViewCell content wrong size on first load How to refresh UICollec...

Swift Delhi Meetup - Chapter 16

"It is good to rub, and polish our brain against that of others"  - Michel Eyquem de Montaigne Absolutely yes when I end up in Swift-Delhi Meetup (Chapter 16) last weekend. A big thanks to OYO Rooms for the sponsorship & their organising team. There was total 5 exciting talks lined up on that day. In this post let me brief each one of them & hope you can find it useful. Developing Apps for Global Audience (Lightning Talk) - Shrey Bansal, OYO Rooms When the app is targeted global market, it is very much necessary to keep in mind its design & development challenges. He gave many instances like - Localisation of text might effect label frames if it has fixed size. A font family may not support for all the languages for example - Chinese text don't have bold effect 😑. Even colours, symbols, could give different meaning over different countries. When he shown "Stock app" in iPhone - Green & Red colors are switched in Indian and Chinese ap...

Protocol Oriented Programming (POP) in Swift

A protocol declares a programmatic interface that any class or structs or enums may choose to implement. It act as blueprints rather than parents. POP is a new approach for programming where you decorate your classes, structs or enums using protocols. By default swift does not support multiple inheritance, therefore problem pops out when you want to add multiple abilities to your class. Protocol OP lets you to add new abilities to a class or struct or enum via protocols which can support multiple implementations. For instance a ‘Car Engine’ protocol can implemented from ‘Petrol engine’’ and  ‘Electric engine’ protocol. Syntax : What about Object Oriented Programming (OOP) ? Creating abstract (methods without implementation) classes or base classes mainly done from inheritance. Every subclasses will have the ability of their super classes (unless ‘final’ method type ). A subclass can override that ability, add specific one. OOP works perfect till y...

Storyboard vs XIB vs Custom UI Code

Have you ever felt difficulty while choosing between Storyboard and XIB or even going for Custom code? Let’s make it easier from this short article. As we know, Storyboard introduced in iOS 5 and it consists of several ViewControllers, whereas XIB (previously NIB) files can consist of only one controller scene. Even custom codes can do all UI actions of such as positioning or animations..etc without help of any GUI tools.  Further, we may not need to stick with only one of above options. We can have one or combinations of three as per the requirement. Pros of Storyboard: As its name says, we can visualize entire scene in a single shot. On the Storyboard file, we can configure the flow between pages directly by using segue. Segues takes care most of UI configurations. Reduces boilerplate code needed to pop, push, present and dismiss view controllers. When storyboard makes sense? A set of views say for example: Authentications (Login/Registration page), Wi...

Implementing autocompletion OTP field in iOS

Long waiting is over. !!  iOS 12 brings Autofill for OTP text field which is close to Android provided a decade back. Previously in iOS we used to toggle between OTP text screen and message inbox.  Which was hard to remember and time consuming resulting a bad user experience. Personally, I have been asked from the client/customer couple of times to implement autocompletion for OTP field and took me a lot of time to convey that it is not possible in iOS. Why Autofill was not possible previously?  We all know that Apple gives at most care for user privacy. When we see iOS architecture, each individual app is like a separate island. There is no inter-app bridge between apps (exception for Keychain and URLSchemes APIs which gives very limited scope). Thus we cannot read message content from inbox. Where to start Autofilling? First of all, the target SMS need to have the OTP Code with prefix string "Code" or "Passcode"on its message content. Beware of OTP c...

Static Vs Dynamic libraries in iOS

A library is a collection of resources and the code itself, compiled for one or more architectures. Apple provides 2 types of library architectures that behaves differently upon building our app. Static libraries (*.a) :  When the app launches Static libraries loaded into address space for future use. They become part of the executable, and are statically linked to client apps. Thus, it (especially large executable libraries) makes apps slower to load and run, even launch time of the apps. Apple shown the architecture of static libraries as below : Dynamic libraries (*.dylib) :  With dynamic libraries, the app loads code into its address space when it’s actually needed, either at launch time or at runtime. The libraries are not part of the executable file. Thus decreases the memory footprint for your app. Clearly dynamic frameworks has got more advantages over static frameworks. Notably, it is available for iOS 8 and above. Apple shown the architecture...

Language Server Protocol (LSP) for Swift

You might already heard “ Apple announced LSP support for Swift ”. This is overwhelming decision by Apple because it’s a great step towards openness from it’s ‘monopoly game’. You can check complete official announcement here by Argyrios Kyrtzidis . What exactly LSP and How it works ? This Post from NSHipster by Matt explains how it works and what are the benefits out of the LSP support. In short, LSP will enable Swift development other than Xcode with below seamless integrated features - Autocompletion Jump to Definition Syntax highlighting Tooltips Automatic formatting and many for editor features. Any editor (say Visual Studio) to understand Swift, it requires Swift package to be integrated. Thus, SourceKit-LSP (Still under development) comes into play. This open source project got contribution from large group of developers and releasing very soon. Later we can easily integrate Swift into any editing tool with the help of any package manager (NodeJS prefer...

Stored Properties vs Computed Properties

We will start with simple a property which can be defined as below : var firstValue : Int let length : Int = 22 We can see it's not defined inside any closure, (A Closure "{ }" is meant for Classes, Structures or Enumerations) Stored Properties are those properties kept inside Classes and Structures. (not enums) . So, it will be always instance of classes or structures. Here is 2 more examples  : struct FixedLengthRange { var firstValue : Int let length : Int } class FixedLengthRange { var firstValue : Int let length : Int } Computed properties are those properties which do not store values, instead it gives getter and optional setter methods to access those property values. struct Circle {   var rad = 0   let pi = 3.14   var area : Float    {      get {        return rad * rad * pi          }   ...

Starting Server side Swift : Kitura

Kitura is a new package based web framework for Swift 3.0 by IBM. As Swift is a compiled language, your Kitura application compiles to a binary that can either act as its own webserver (by default, on port 8090) or as a FastGCI server for use with Nginx or Apache.         Features URL routing (GET, POST, PUT, DELETE) URL parameters Static file serving FastCGI support SSL/TLS support JSON parsing Pluggable middleware Starting first project To create executable package, create and switch to a directory. For  example I have created a directory with name ‘ Todoapp ’ and moved in. Now in the terminal,  $ swift package init will create folder structure for Kitura as shown Todoapp ├── Package.swift ├── Sources │   └── main.swift └── Tests Tip : In case swift file ~/Sources/Todoapp.swift created then rename to ~/Sources/main.swift. In the  Package.swift  add  ‘dependencies’. /***** Package.swi...

SVN configuration in MAC Android Studio

To setup svn and checkout repository in Android Studio 2.2.2 for Mac , we have to follow simple few steps .   Step 1: Go to Android Studio Preferences  >  Version Control > Subversions Select checkbox for command line client Now, type ` svn ` in the box. click on ' Apply ' and ' Save ' Step 2: From the top menu, VCS > Checkout from Version Control Paste SVN path in the under repository path after hitting ‘+’ button. Then you can see you repository listed for checkout.   If you expand the newly added repository, can see all the folders. Click on parent folder and click ' Checkout ' to your work space.

iOS Senior Level [Part 4/4] : Final page

[1] Foundation vs Core Foundation CoreFoundation is a general-purpose C framework whereas Foundation is a general-purpose Objective-C framework. Both provide collection classes, run loops, etc, and many of the Foundation classes are wrappers around the CF equivalents. CF is mostly open-source , and Foundation is closed-source. Core Foundation is the C-level API, which provides CFString, CFDictionary and the like. Foundation is Objective-C, which provides NSString, NSDictionary, etc. CoreFoundation is written in C while Foundation is written in Objective-C. Foundation has a lot more classes CoreFoundation is the common base of Foundation and Carbon. [2] iOS Directories ~/Documents, ~/Documents/Inbox [both will store user generated files that can be exposed to user. Ex. email attachments] ~/Library [files not to user.] ~/tmp [System clears files if app not running. Not backed up by iTunes] [3] Concurrency Operations Operations can be configured to run a block of code synchronously or as...

Popular posts from this blog

Implementing autocompletion OTP field in iOS

Long waiting is over. !!  iOS 12 brings Autofill for OTP text field which is close to Android provided a decade back. Previously in iOS we used to toggle between OTP text screen and message inbox.  Which was hard to remember and time consuming resulting a bad user experience. Personally, I have been asked from the client/customer couple of times to implement autocompletion for OTP field and took me a lot of time to convey that it is not possible in iOS. Why Autofill was not possible previously?  We all know that Apple gives at most care for user privacy. When we see iOS architecture, each individual app is like a separate island. There is no inter-app bridge between apps (exception for Keychain and URLSchemes APIs which gives very limited scope). Thus we cannot read message content from inbox. Where to start Autofilling? First of all, the target SMS need to have the OTP Code with prefix string "Code" or "Passcode"on its message content. Beware of OTP c...

Animating label text update - choosing a better way

Recently I published a countdown app .  At one point of development - I have to show a timer on a UILabel which ticks on each seconds. As usual I started  setting text to a label object - self .timerLabel.text = someString Easy piece of cake right !?   But wait ... it won't take much user attention when timer ticks on every seconds. So I decided to make use of a simple animation while label gets text update. I found there are dozens of ways to animate a label. In this short article, I listed 3 best way you can animate text on a label. ( Spoiler Alert 👀- I decided to go with 3rd option)  1. Fade In - Fade out animation : CATransition class has got transition type `fade`. With timing function of CATransition - I was able to see the below result. let animation: CATransition = CATransition () animation.timingFunction = CAMediaTimingFunction (name: CAMediaTimingFunctionName .easeInEaseOut) animation.type = CATransitionType .fade animation.subtype = C...

Cached Async Image in SwiftUI

 SwiftUI’s AsyncImage is handy, but every time your view appears, it refetches the image—leading to flicker, delays, and unnecessary network use. What if you could fetch once, then reuse instantly? That's exactly what the Cached Async Image  delivers: a memory-powered caching layer that keeps SwiftUI image loading smooth, snappy, and resilient. First a simple in-memory cache without disk persistence. This will be thread-safe and auto-purges under memory pressure. A Singleton wrapping NSCache for URL → UIImage caching as follows : final class ImageCache {   static let shared = ImageCache()   private init() {}   private let cache = NSCache<NSURL, UIImage>()   func image(for url: URL) -> UIImage? {     cache.object(forKey: url as NSURL)   }   func insertImage(_ image: UIImage?, for url: URL) {     guard let image else { return }     cache.setObject(image, forKey: url as NSURL)   }   func clearAll() { ...

Prevent Navigationbar or Tabbar overlapping Subview - solved for Card view

Recently, I started with a Card view added as a subview of UIView in a view-controller. When a view controller created along subviews, it tends to use entire screen bounds and also slips behind Tab bar or Navigation bar. In my current situation, it's second case. Casually new iOS developers will write a patch by additional value for coordinate y and subtracting bar height from its size. A lot of them posted in SO threads too : How to prevent UINavigationBar from covering top of view? View got hidden below UINavigationBar iOS 7 Navigation Bar covers some part of view at Top So, how I got solved ? self.edgesForExtendedLayout = [] This  will avoid all subviews in a view controller get behind any bars. Read full apple  documentation on here. Full Source code below :  //Simple view controller where its view layed-out as a card. class WidgetCardViewController : UIViewController { var containerView = UIView () //MARK:- View Controller Life Cyc...

UICollectionViewCell shows with wrong size on First time - Solved

We commonly use Collection view where its cell size calculated run time. The flow layout delegate is responsible to return individual cell sizes. BUT in most of the cases, delegate method `collectionView: layout sizeForItem:` expects cell size too early. Before generating actual cell size. extension YourViewController : UICollectionViewDelegateFlowLayout { func collectionView ( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize (width: externalWidth, height: externalHeight) } } For instance, if a cell size depends on external view and its frame is not yet ready - results with wrong (or outdated) cell size. Typically happens for the first time view controller laid out all views. You can find similar queries in StackOverflow community : Collection view sizeForItemNotWorking UICollectionViewCell content wrong size on first load How to refresh UICollec...