Stack Implementation in swift


public struct Stack{
 private var array:[T]
 public var maxSize:Int?

 public init(){
    array = []
 }


//MARK: isEmpty
 public var isEmpty:Bool{
 return array.count == 0
 }

//MARK: count
 public var count:Int{
 return array.count
 }
 //MARK: PUSH
 public mutating func push(element:T){
 if (maxSize != nil){
 if array.count >= maxSize{
 print("OverFlow")
 }
 }
 array.append(element)
 }
 //MARK: POP
 public mutating func pop()->T?{
 if isEmpty{
 return nil
 }
 return array.removeLast()
 }

//MARK: get Peek element
 public func peek()->T?{
 return array.last
 }
}

//use this stack
var myStack = Stack()
myStack.push(10)
myStack.pop()
Advertisements

Queue implementation in swift


public struct Queue<T>{

    private var array:[T]

    public init(){

        array = []

    }

    //MARK: isEmpty

    public var isEmpty:Bool{

        return array.count == 0

    }

    //MARK: count

    public var count:Int{

        return array.count

    }

    //MARK: enqueue

    public mutating func enqueue(element:T){

        array.append(element)

    }

    //MARK: dequeue

    public mutating func dequeue()->T?{

        if isEmpty{

            return nil

        }

        return array.removeFirst()

    }

    //MARK: get Peek element

    public func peek()->T?{

        return array.last

    }

}

// this queue

var myQueue = Queue<Int>()

myQueue.enqueue(10)

myQueue.dequeue()

UIApplication and its Delegate


1. UIApplication :  root class UIResponder

  • A major role of your app’s application object is to handle the initial routing of incoming user events
  • he application object maintains a list of open windows (UIWindow objects) and through those can retrieve any of the app’s UIView objects
  • The UIApplication class defines a delegate that conforms to the UIApplicationDelegate protocol and must implement some of the protocol’s methods.
  • The application object informs the delegate of significant runtime events—for example, app launch, low-memory warnings, and app termination—giving it an opportunity to respond appropriately.

Some Other Task

2. UIApplicationDelegate : root class NSObjectProtocol

The UIApplicationDelegate protocol defines methods that are called by the singleton UIApplication object in response to important events in the lifetime of your app.

The app delegate performs several crucial roles:

  • It contains your app’s startup code.
  • It responds to key changes in the state of your app. Specifically, it responds to both temporary interruptions and to changes in the execution state of your app, such as when your app transitions from the foreground to the background.
  • It responds to notifications originating from outside the app, such as remote notifications (also known as push notifications), low-memory warnings, download completion notifications, and more.
  • It determines whether state preservation and restoration should occur and assists in the preservation and restoration process as needed.
  • It responds to events that target the app itself and are not specific to your app’s views or view controllers.
  • You can use it to store your app’s central data objects or any content that does not have an owning view controller.

FitBit AOuth in iOS app


The Fitbit API allows developers to interact with Fitbit data in their own applications, products and services. The API allows for most of the read and write methods that you will need to support your application. If you have uses or needs that are not currently supported by the API, drop by the Dev Forum and let us know! We look forward to working closely with the development community to make the Fitbit API a system that enables you to do awesome, mind blowing stuff.

You can fetch fitbit data in your health app , please follow following procedure.

  1. Resister your application in fit bit developer account https://dev.fitbit.com/apps/new
  1. Copy Client Id and consumer_secret , It will be used in your Application.
  2. Download FitBit-Auth-for-iOS from http://msyshani.github.io/FitBit-Auth-for-iOS/ Drag and drop MSYFitBit.swift in your application. Dard and drop OAuthSwift files in your project. In AppDelegate

func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
if (url.host == "fivedotsFitbit") {
OAuthSwift.handleOpenURL(url)
}
return true
}

In Your ViewController

MSYFitBit.shareFitBit.fetchDataFromFitbit { (result, success) -> Void in

}

CoreData Day-1 :: What is coreData ?


cropped-mobile.jpg

Core Data:: Core Data is an object graph and persistence framework provided by Apple in the Mac OS X and iOS operating systems. It was introduced in Mac OS X 10.4 Tiger and iOS with iPhone SDK 3.0. It allows dataorganised by the relational entity–attribute model to be serialised into XML, binary, or SQLite stores.

Core Data Features

The Core Data framework provides generalized and automated solutions to common tasks associated with object life-cycle and object graphmanagement, including persistence. Its features include:

  • Change tracking and undo support.Core Data provides built-in management of undo and redo beyond basic text editing.
  • Relationship maintenance.Core Data manages change propagation, including maintaining the consistency of relationships among objects.
  • Futures (faulting).Core Data can reduce the memory overhead of your program by lazily loading objects. It also supports partially materialized futures, and copy-on-write data sharing.
  • Automatic validation of property values.Core Data’s managed objects extend the standard key-value coding validation methods that ensure that individual values lie within acceptable ranges so that combinations of values make sense.
  • Schema migration.Dealing with a change to your application’s schema can be difficult, in terms of both development effort and runtime resources. Core Data’s schema migration tools simplify the task of coping with schema changes, and in some cases allow you to perform extremely efficient in-place schema migration.
  • Optional integration with the application’s controller layer to support user interface synchronization.Core Data provides the NSFetchedResultsController object on iOS, and integrates with Cocoa Bindings on OS X.
  • Full, automatic, support for key-value coding and key-value observing.In addition to synthesizing key-value coding and key-value observing compliant accessor methods for attributes, Core Data synthesizes the appropriate collection accessors for to-many relationships.
  • Grouping, filtering, and organizing data in memory and in the user interface.
  • Automatic support for storing objects in external data repositories.
  • Sophisticated query compilation.Instead of writing SQL, you can create complex queries by associating an NSPredicate object with a fetch request. NSPredicate provides support for basic functions, correlated subqueries, and other advanced SQL. With Core Data, it also supports proper Unicode, locale-aware searching, sorting, and regular expressions.
  • Merge policies.Core Data provides built in version tracking and optimistic locking to support automatic multi-writer conflict resolution.

Why Should You Use Core Data?

There are a number of reasons why it may be appropriate for you to use Core Data. One of the simplest metrics is that, with Core Data, the amount of code you write to support the model layer of your application is typically 50% to 70% smaller as measured by lines of code. This is primarily due to the features listed above—the features Core Data provides are features you don’t have to implement yourself. Moreover they’re features you don’t have to test yourself, and in particular you don’t have to optimize yourself.

Core Data has a mature code base whose quality is maintained through unit tests, and is used daily by millions of customers in a wide variety of applications. The framework has been highly optimized over several releases. It takes advantage of information provided in the model and runtime features not typically employed in application-level code. Moreover, in addition to providing excellent security and error-handling, it offers best memory scalability of any competing solution. Put another way: you could spend a long time carefully crafting your own solution optimized for a particular problem domain, and not gain any performance advantage over what Core Data offers for free for any application.

In addition to the benefits of the framework itself, Core Data integrates well with the OS X tool chain. The model design tools allow you to create your schema graphically, quickly and easily. You can use templates in the Instruments application to measure Core Data’s performance, and to debug various problems. On OS X desktop, Core Data also integrates with Interface Builder to allow you to create user interfaces from your model. These aspects help to further shorten your application design, implementation, and debugging cycles.

What Core Data Is Not

Having given an overview of what Core Data is and does, and why it may be useful, it is also useful to correct some common misperceptions and state what it is not.

  • Core Data is not a relational database or a relational database management system (RDBMS).Core Data provides an infrastructure for change management and for saving objects to and retrieving them from storage. It can use SQLite as one of its persistent store types. It is not, though, in and of itself a database. (To emphasize this point: you could for example use just an in-memory store in your application. You could use Core Data for change tracking and management, but never actually save any data in a file.)
  • Core Data is not a silver bullet.Core Data does not remove the need to write code. Although it is possible to create a sophisticated application solely using the Xcode data modeling tool and Interface Builder, for more real-world applications you will still have to write code.
  • Core Data does not rely on Cocoa bindings.Core Data integrates well with Cocoa bindings and leverages the same technologies—and used together they can significantly reduce the amount of code you have to write—but it is possible to use Core Data without bindings. You can readily create a Core Data application without a user interface

How to use Swift code in Objective C class


Screen Shot 2015-04-24 at 5.03.18 PM

Now you can easily use swift code in your objective C class.

Step 1. Go to packaging in Build setting and get Product Module Name. Change it or write any other name. see attached image.

Step 2. Go to Object c class in which you want to use Swift class. and import class as following.

#import “msy-Swift.h”

Where msy – Product Module Name

You don’t need to import all swift class .this line import all swift classes in your project in your class.

Step 3::

Assume your swift class method is


class func commonAlert(title:String,msg:String,curView:UIViewController){

        var device : UIDevice = UIDevice.currentDevice();

        var systemVersion = device.systemVersion;

        var iosVerion : Float = (systemVersion as NSString).floatValue

        if(iosVerion >= 8.0) {

    

        var alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: “Ok”, style: UIAlertActionStyle.Default, handler: nil))

                  // return alert

            curView.presentViewController(alert, animated: true, completion: nil)

        }else{

            let alert=UIAlertView(title: title, message: msg, delegate: self, cancelButtonTitle: “ok”)

            alert.show()

           

        }

    }


You can call this func using your objective c code like following

[CommonClass commonAlert:@”Hi ” msg:@”How to use Swift code in Objective C class” curView:self];

Best Of Luck

Making a class singleton in Swift


Making a class singleton  in Swift

Create a singleton class

import UIKit

import AVFoundation

class TextToSpeech: NSObject {

   

    let speechSyn=AVSpeechSynthesizer()

    var speechUlt=AVSpeechUtterance(string: “”)

    

    

    class var shareInstance:TextToSpeech{

      struct Static{

        static var onceToken:dispatch_once_t=0

        static var instance:TextToSpeech?=nil

        }

        

        dispatch_once(&Static.onceToken){

            Static.instance=TextToSpeech()

        }

        

        return Static.instance!

    }

    

    

    func pleaseSpeechThisText(text:NSString){

        speechUlt=AVSpeechUtterance(string: text)

        speechUlt.voice = AVSpeechSynthesisVoice(language: “en-au”)

        speechUlt.rate=0.3

        speechSyn.speakUtterance(speechUlt)

        

    }

    

}

Call this class as

TextToSpeech.shareInstance.pleaseSpeechThisText(“Hi I am an iOS Developer”)

Block as a completion Handler in iOS


Block as a completion Handler in iOS

In Objective-c

declare a méthode::

-(void) getCallBack:(NSString *)string1 onCompletion:(void(^)(NSString *sting))handeler;

function implementation:

-(void) getCallBack:(NSString *)string1 onCompletion:(void(^)(NSString *sting))handeler{

    

    handeler(string1);

}

function calling:

[self  getCallBack:@”Sunny” onCompletion:^(NSString *value){

        NSLog(@”My name is %@”,value);

    }];

In Swift

function declaration::

func getValueByMultiPle(value1:Int,value2:Int,onCompletion:((success:Int)->Void),onError:((errorValue:String)->Void)){

        

        if(value1>0 && value2>0){

            onCompletion(success: value1*value2)

        }else{

            onError(errorValue:“Error”)

        }

    

    }

function calling ::

User.shareInstance.getValueByMultiPle(0, value2:10, onCompletion: { success in

                println(success)

            }, onError: { error in

                println(error)

        })

Common method in Swift


1. Check for any field empty in NSDictionary

class func checkforEmptyValueinDictioanty(dic:NSDictionary)-> Bool{

for (keyVal, dataVal) in dic {

  if (dataVal.length()==0){

                println(\(keyVal): \(dataVal.length()))

                return false

            }

            

        }

        return true

    }

2.Email validation

class func isValidEmail(testStr:String) -> Bool {

let fullNameArr = testStr.componentsSeparatedByString(“@”)

        var firstPart: String = fullNameArr[0]

        if let range = firstPart.rangeOfCharacterFromSet(NSCharacterSet.letterCharacterSet()){

 }else{

            return false

        }

      let emailRegEx = “[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}”

 var emailTest = NSPredicate(format:“SELF MATCHES %@”, emailRegEx)

        let result = emailTest.evaluateWithObject(testStr)

        return result

    }

3. Alert in Swift

class func commonAlert(title:String,msg:String,curView:UIViewController){

        var device : UIDevice = UIDevice.currentDevice();

        var systemVersion = device.systemVersion;

        var iosVerion : Float = (systemVersion as NSString).floatValue

        if(iosVerion >= 8.0) {

    

        var alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.Alert)

            alert.addAction(UIAlertAction(title: “Ok”, style: UIAlertActionStyle.Default, handler: nil))

                  // return alert

            curView.presentViewController(alert, animated: true, completion: nil)

        }else{

            let alert=UIAlertView(title: title, message: msg, delegate: self, cancelButtonTitle: “ok”)

            alert.show()

           

        }

    }

4. NSUserDefaults in swift as common function

class func saveToUserDefault(value:AnyObject, key:String)

    {

        NSUserDefaults.standardUserDefaults().setObject(value, forKey:key)

        NSUserDefaults.standardUserDefaults().synchronize()

    }

    

    class func userDefaultForKey(key:String) -> String

    {

        return NSUserDefaults.standardUserDefaults().objectForKey(key) as NSString

        

    }

    class func userDefaultForAny(key:String) -> AnyObject

    {

        return NSUserDefaults.standardUserDefaults().objectForKey(key) as AnyObject!

    }

    

    class func userdefaultForArray(key:String) -> Array<AnyObject>

    {

        return NSUserDefaults.standardUserDefaults().objectForKey(key) as Array

    }

    

    class func removeFromUserDefaultForKey(key:String)

    {

        NSUserDefaults.standardUserDefaults().removeObjectForKey(key)

        NSUserDefaults.standardUserDefaults().synchronize()

        

    }

5.Get screen height and width

let _screenWidth=UIScreen.mainScreen().bounds.size.width

let _screenHeight=UIScreen.mainScreen().bounds.size.height

Use different font text in a Label in swift


let secondLabel=UILabel(frame: CGRectMake(0, 16, _screenWidth2, 20))

        secondLabel.textColor=UIColor.whiteColor()

        secondLabel.textAlignment=NSTextAlignment.Center

        secondLabel.font=UIFont(name: “Arial”, size: 12)

        bottomView.addSubview(secondLabel)

        

        let attrSting=NSMutableAttributedString(string: “I agree to the Terms of Service and Privacy Policy.”)

        

        NSLog(“text length is %d”, attrSting.length)

        

        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica-bold”, size: 14), range: NSMakeRange(15, 16))

        

        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica”, size: 12), range: NSMakeRange(31,4 ))

        

        attrSting.addAttribute(NSFontAttributeName, value: UIFont(name: “Helvetica-bold”, size: 14), range: NSMakeRange(35, 15))

        

        secondLabel.attributedText=attrSting