Tuesday 27 December 2016

Enums - Structs - Classes in Swift

Enums:
  • An enumeration defines a common type for a group of related values.
  • Enums are value types that have a set of cases, where each case can have different associated values. 
  • Each value of an enum type represents a single case as defined by the enum. 
  • They can’t have any stored properties.(let, var)

Syntax:
enum SomeEnumeration {
  // enumeration definition goes here
}


Structs:


Common features for Classes and Structs:

  • Define properties to store values 
  • Define methods to provide functionality 
  • Define subscripts to provide access to their values using subscript syntax 
  • Define initializers to set up their initial state 
  • Be extended to expand their functionality beyond a default implementation 
  • Conform to protocols to provide standard functionality of a certain kind
Extra benefits of classes:
  • Inheritance enables one class to inherit the characteristics of another. 
  • Type casting enables you to check and interpret the type of a class instance at runtime. 
  • Deinitializers enable an instance of a class to free up any resources it has assigned. 
  • Reference counting allows more than one reference to a class instance.
Syntax:
struct SomeStructure { 
   // structure definition goes here
}


Classes:

Unlike value types, reference types are not copied when they are assigned to a variable or constant, or when they are passed to a function. Rather than a copy, a reference to the same existing instance is used instead.
Syntax:
class SomeClass {  
  // class definition goes here
}

Sunday 10 July 2016

Updating remote GIT branch list on local machine

If you are sure that remote server repository contains more branches and they are not shown in your IDE like, XCode., then try the below commands to refresh the local list of repositories.

Command 1:
$ git branch -a
OR
$ git branch -r
Then you have to update your remote list, by:

Command 2:
$ git remote update origin --prune

Monday 27 June 2016

Creating a UIColor from a hex string

Swift 2.0 version of solution which will handle alpha value of color and with perfect error handling is here:
    func RGBColor(hexColorStr : String) -> UIColor?{
   
        var red:CGFloat = 0.0
        var green:CGFloat = 0.0
        var blue:CGFloat = 0.0
        var alpha:CGFloat = 1.0
   
        if hexColorStr.hasPrefix("#"){
       
            let index   = hexColorStr.startIndex.advancedBy(1)
            let hex     = hexColorStr.substringFromIndex(index)
            let scanner = NSScanner(string: hex)
            var hexValue: CUnsignedLongLong = 0
       
            if scanner.scanHexLongLong(&hexValue)
            {
                if hex.characters.count == 6
                {
                    red   = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
                    green = CGFloat((hexValue & 0x00FF00) >> 8)  / 255.0
                    blue  = CGFloat(hexValue & 0x0000FF) / 255.0
                }
                else if hex.characters.count == 8
                {
                    red   = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
                    green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
                    blue  = CGFloat((hexValue & 0x0000FF00) >> 8)  / 255.0
                    alpha = CGFloat(hexValue & 0x000000FF)         / 255.0
                }
                else
                {
                    print("invalid hex code string, length should be 7 or 9", terminator: "")
                    return nil
                }
            }
            else
            {
                print("scan hex error")
           return nil
            }
        }
   
        let color: UIColor =  UIColor(red:CGFloat(red), green: CGFloat(green), blue:CGFloat(blue), alpha: alpha)
        return color
    }

Generating QR code image in iOS SWIFT

Code to generate QR image in Swift 2.0.
Add Apple's 'Core media' framework to project.

    let reqStr = “string to convert as QR code”
    let data = reqStr.dataUsingEncoding(NSISOLatin1StringEncoding, allowLossyConversion: false)
                
    let filter = CIFilter(name: "CIQRCodeGenerator")
    filter!.setValue(data, forKey: "inputMessage")
                
    let qrImage:CIImage = filter!.outputImage!
        
    //qrImageView is a IBOutlet of UIImageView        
    let scaleX = qrImageView.frame.size.width / qrImage.extent.size.width
    let scaleY = qrImageView.frame.size.height / qrImage.extent.size.height
                
    let resultQrImage = qrImage.imageByApplyingTransform(CGAffineTransformMakeScale(scaleX, scaleY))
    qrImageView.image = UIImage(CIImage: resultQrImage)
               

Wednesday 25 March 2015

Programatically finding current country code and name in iOS

NSLocale *countryLocale = [NSLocale currentLocale]; 
NSString *countryCode = [countryLocale objectForKey:NSLocaleCountryCode]; 
NSString *country = [countryLocale displayNameForKey:NSLocaleCountryCode value:countryCode]; 

NSLog(@"Country Code:%@ Name:%@", countryLocale, countryCode, country); 
//Country Code:IN Name:India

Friday 19 December 2014

Tips to increase the performance of iOS apps

1) Reuse UITableViewCell objects 
Use a reuseIdentifier Where Appropriate a table view's data source should generally reuse UITableViewCell objects when it assigns cells to rows in tableView:cellForRowAtIndexPath:
 A table view maintains a queue or list of UITableViewCell objects that the data source has marked for reuse.

If you don’t, your table view will configure a brand-new cell each time a row is displayed. This is an expensive operation and will definitely affect the scrolling performance of your app

static NSString *cellIdentifier = @"MyCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

2) Set Views as Opaque When Possible
If you have opaque views — that is, views that have no transparency defined — you should set their opaque property to YES.

This will allow the system to draw your views in an optimal manner. It’s a simple property that can be set in both Interface Builder and code.

This property provides a hint to the drawing system as to how it should treat the view. If set to YES, the drawing system treats the view as fully opaque, which allows the drawing system to optimize some drawing operations and improve performance.
If set to NO, the drawing system composites the view normally with other content. The default value of this property is YES.

3) Avoid Heavy XIBs
Try to create one XIB per view controller, and if possible, break out a view controller’s view hierarchy into separate XIBs.
Note that when you load a XIB into memory, all of its contents are loaded into memory, including any images. 
If you have a view you’re not using immediately, then you’re wasting precious memory. It’s worth noting that this won’t happen with storyboards, since a storyboard will only instantiate a view controller when it’s needed.

4) Size Images to Image Views
If you’re displaying an image from the app’s bundle in a UIImageView, make sure that the image and the UIImageView are same size.

5) Enable GZIP Compression
A significant and growing number of apps rely on external data from remote servers or other external APIs.
At some point you’ll be developing an app that downloads data in XML, JSON, HTML or some other text format.
The problem is that the network condition cannot be relied upon when it comes to mobile devices.
A user can be on an EDGE network one minute, and the a 3G network the next. 
Whatever the scenario, you don’t want to keep your user waiting!
One option to reduce the file size and speed up the download of network-based resources is by enabling 
GZIP compression on both your server and on your client.
This is especially useful for text-based data, which has a high potential ratio for compression.
The good news is that iOS already supports GZIP compression by default if you’re using NSURLConnection, or a framework built on top of it such as AFNetworking. Even more good news is that some cloud providers, such as Google App Engine already send compressed responses.

6) Caching 
A great rule of thumb when developing your app is to “cache the things that are unlikely to change, but are accessed frequently".
You can cache remote server responses, images, or even calculated values.

7) Consider Drawing
There are several ways to make great-looking buttons in iOS. 
You can use full sized images, resizable images, or you could go the distance and draw it manually using CALayer, CoreGraphics or even OpenGL.

Important Note:
The short story is that using pre-rendered images is faster, because iOS doesn’t have to create an image and draw shapes on it to finally draw into than screen (the image is already created). 
The problem is that you need to put all those images in your app’s bundle, increasing its size. 
That’s why using resizable images is so great: you save space by removing “wasted” image space that iOS can repeat for you. 

However, by using images you lose the ability to tweak your images by code, needing to regenerate them every and putting them into the app again and again. That can be a slow process.
 Another point is that if you have an animation or just a lot of images with slightly changes, you’ll have to embed a lot of images, growing the app’s bundle size.
You also don’t need to generate different images for different elements (e.g. buttons).

8)  Reuse Expensive Objects
Some objects are very slow to initialize — NSDateFormatter and NSCalendar are two examples. 
However, you can’t always avoid using them, such as when parsing dates from a JSON/XML response.
To avoid performance bottlenecks when working with these objects, try to reuse these objects if at all possible. 
You can do this by either adding a property to your class, or by creating a static variable.

9) Use Sprite Sheets
In games development sprite sheets make drawing faster and can even consume less memory than standard screen drawing methods.

10) Avoid Re-Processing Data
Many apps make calls for data from remote servers to get information the app requires to function. 
This data usually comes across in JSON or XML format.
 It’s important to try and use the same data structure at both ends when requesting and receiving the data.

11) Choose the Right Data Format
There are multiple ways you can transfer data to your app from a web service, but the most common two are JSON and XML. 
You want to make sure you choose the right one for your app.
JSON is faster to parse, and is generally smaller than XML, which means less data to transfer. 
And since iOS 5, there’s built-in JSON deserialization so it’s easy to use as well.
However, one advantage XML has is that if you use the SAX parsing method, you can work with XML data as you read it off the wire, instead of having to wait for the entire data to arrive before you parse it like JSON. 

12) Set Background Images Appropriately
Like many other things in iOS coding, there’s at least two different ways to place a background image on your view:
You can set your view’s background color to a color created with UIColor’s colorWithPatternImage.
You can add a UIImageView subview to the view.
If you have a full size background image, then you should definitely use a UIImageView because UIColor’s colorWithPatternImage was made to create small pattern images that will be repeated, and not large images size. 
Using UIImageView will save a lot of memory in this case.
This can give you increased performance and reduced memory consumption when you are dealing with very large sets of data.

13) Choose Correct Data Storage Option
We have several options for storing and reading large data sets:
  • NSUserDefaults
  • Structured file in XML, JSON, or Plist format
  • Archive using NSCoding
  • Local SQL database such as SQLite
  • Core Data

 NSUserDefaults:
 Although NSUserDefaults is nice and easy, it’s really only good if you have a very small amount of data to save (like what level you’re on, or whether sound is turned on and off). 
Once you start getting large amounts of data, other options are better.

Structured file in XML, JSON, or Plist format:
Saving to a structured file can be problematic as well. Generally, you need to load the entire file into memory before you can parse it, which is an expensive operation. 
You could use SAX to process a XML file, but that’s a complex solution. As well, you’d end up having all objects loaded in memory — whether you want them there or not.

NSCoding:
Unfortunately, it also reads and writes to a file, so it experiences the same problems as above.

SQLite and Core Data:
Your best bet in this situation is to use SQLite or Core Data. By using these technologies, you can perform specific queries to only load the objects you need and avoid a brute-force searching approach to retrieve the data. 
In terms of performance, SQLite and Core Data are very similar.

The big difference between SQLite and Core Data is really about the general usage of each. Core Data represents an object graph model, while SQLite is just a regular DBMS. Usually Apple recommends that you go with Core Data, but 
if you have a particular reason you want to avoid it, you can go lower level to SQLite.

14) Speed up Launch Time
Launching your app quickly is very important, especially when the user launches for the first time. 
First impressions mean a lot for an app!
The biggest thing that you can do to ensure your app starts as quickly as possible is to perform as many asynchronous tasks as possible, such as network requests, database access, or parsing data.
As well, try to avoid fat XIBs, since they’re loaded on the main thread.


Swift Programming Basics Part-1

Swift is an innovative new programming language for Cocoa and Cocoa Touch released at WWDC. 
Swift code works side-by-side with Objective-C.
When talking about Swift, Apple refers to three key considerations: Safe, Modern and Powerful.

Features of Swift:
  • Modern
Swift is the result of the latest research on programming languages, combined with decades of experience building Apple platforms. Named parameters brought forward from Objective-C are expressed in a clean syntax that makes APIs in Swift even easier to read and maintain.
Ex:
var sortedStrings = sorted(stringArray)
 {
$0.uppercaseString < $1.uppercaseString
 }
  • Designed for Safety
Swift eliminates entire classes of unsafe code. Variables are always initialized before use, arrays and integers are checked for overflow, and memory is managed automatically. Syntax is tuned to make it easy to define your intent — for example, simple three-character keywords define a variable (var) or constant (let).

The safe patterns in Swift are tuned for the powerful Cocoa and Cocoa Touch APIs. Understanding and properly handling cases where objects are nil is fundamental to the frameworks, and Swift code makes this extremely easy. Adding a single character can replace what used to be an entire line of code in Objective-C. This all works together to make building iOS and Mac apps easier and safer than ever before.

  • Fast and Powerful
From its earliest conception, Swift was built to be fast. Using the incredibly high-performance LLVM compiler, Swift code is transformed into optimized native code, tuned to get the most out of modern Mac, iPhone, and iPad hardware. The syntax and standard library have also been tuned to make the most obvious way to write your code also perform the best.

Swift is a successor to the C and Objective-C languages. It includes low-level primitives such as types, flow control, and operators. It also provides object-oriented features such as classes, protocols, and generics, giving Cocoa and Cocoa Touch developers the performance and power they demand.

  • Interactive Playgrounds
A playground is a new type of file that allows you to test out Swift code, and see the results of each line in the sidebar. For example, add the following lines to your playground:
let tutorialTeam = 60
let editorialTeam = 17
let totalTeam = tutorialTeam + editorialTeam
Playgrounds make writing Swift code incredibly simple and fun. Type a line of code and the result appears immediately. If your code runs over time, for instance through a loop, you can watch its progress in the timeline assistant. The timeline displays variables in a graph, draws each step when composing a view, and can play an animated SpriteKit scene. When you’ve perfected your code in the playground, simply move that code into your project.


Prerequisites for starting Swift programming:

  • A mac running OSX Mavericks or Yosemite
  • A copy of Xcode 6

            ***********************

Declaring variables in Swift:

Variables allow you to store data.
To declare a variable you have to use the keyword "var"

Ex:

var myString: String = "Hello World" 
//This line of code instructs the system that you want to create a variable named myString which is of type String and it will contain the text, “Hello World”.
                          (or)
var myString = "Hello World"
//Swift is smart enough to infer that if you are assigning a string to a variable and in fact that variable will be of type string. So you need not explicitly specify the type as in the above example

Variables can be modified once created so we could add another line and change "Hello World" to something else

myString = "Hello"

Other Exps on Variables:

var sal: Double = 70000.0
or
var sal = 70000.0  //Double

Constants or  Immutable Variables:

To create an immutable variable or constant you need to use the keyword 'let'.
Ex:
let someConstant = 10

Constants cannot be modified once created

someConstant = 20 //Compiler error

Other Exs:


let myNum: Int = 204

or
let myNum = 204  // Int

let isReal: Bool = true

or
let isReal = true  //Bool


Collection Types:
Collection Types are of 2 types.
Arrays  and Dictionarys

Arrays :

Array is a collection of data items which can be accessed via an index beginning with 0.

Ex:

var nameArray = ["Teja", "Kumar", "Varma", "Raja"]
or
var nameArray: [String] = ["Jack", "Queen", "King"]

==>Modifing An Array::

Consider an array alphaNumbers
var alphaNumbers = ["One", "Two", "Three"]

-->To add another item to alphaNumbers we use the ‘+=’ operator.
alphaNumbers += "Four"

-->To add multiple items to alphaNumbers array we should simply append an array.
alphaNumbers += ["Five", "Six"]

-->To replace an existing item in the array simply subscript that item and provide a new value:
alphaNumbers [0] = "1n"

Dictionaries:

var colorsDictionary = ["PrimaryColor":"Green", "SecondaryColor":"Red"]