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

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-2 :: CoreData Components ?


cropped-mobile.jpg

1.NSIncrementalStore: NSIncrementalStore is an abstract superclass defining the API through which Core Data communicates with a store. This interface is designed to allow you to create persistent stores which load and save data incrementally, allowing for the management of large and/or shared datasets


2. NSIncrementalStoreNode : NSIncrementalStoreNode is a concrete class to represent basic nodes in a Core Data incremental store.

A node represents a single record in a persistent store.

You can subclass NSIncrementalStoreNode to provide custom behavior.


3. NSManagedObjectModel : The managed object model is the data model of the application. Even though Core Data isn’t a database, you can compare the managed object model to the schema of a database, that is, it contains information about the models or entities of the object graph, what attributes they have, and how they relate to one another.

The NSManagedObjectModel object knows about the data model by loading one or more data model files during its initialization. We’ll take a look at how this works in a few moments.

– (NSManagedObjectModel *)managedObjectModel

{

    if (_managedObjectModel != nil) {

        return _managedObjectModel;

}

    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@”Core_Data” withExtension:@”momd”];

    _managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];

    return _managedObjectModel;

}

Delete Rule in NSManagedObjectModel

The Delete Rule menu has four options, No ActionNullifyCascade, and Deny.

No Action

If you select No Action, Core Data doesn’t update or notify the source record of the relationship. This means that the source record of the relationship still thinks it has a relationship with the record that was deleted. Note that this is rarely what you want.

Nullify

This option sets the destination of the relationship to null when the destination record is deleted. This is the default delete rule of a relationship.

Cascade

If the relationship from Person to Address is set to Cascade, deleting a person record will also delete any address records that are associated with the person record. This is useful, for example, if a relationship is required and the record cannot or shouldn’t exist without the relationship. A user, for example, shouldn’t exist if it’s not associated with an account.

Deny

In a sense, Deny is the inverse of Cascade. For example, if we have an Accountentity that has a to-many relationship with a User entity with its delete rule set to Deny, an account record can only be deleted if it has no user records associated with it. This ensures that no user records exist without an account record. The result is similar to the Cascade delete rule, but the implementation differs.


4. NSPersistentStoreCoordinator : As its name indicates, the NSPersistentStoreCoordinator object persists data to disk and ensures the persistent store(s) and the data model are compatible. It mediates between the persistent store(s) and the managed object context(s) and also takes care of loading and caching data. That’s right. Core Data has caching built in.

The persistent store coordinator is the conductor of the Core Data orchestra. Despite its important role in the Core Data stack, we rarely interact with it directly.

– (NSPersistentStoreCoordinator *)persistentStoreCoordinator

{

    if (_persistentStoreCoordinator != nil) {

        return _persistentStoreCoordinator;

    }

    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@”Core_Data.sqlite”];

    NSError *error = nil;

    _persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];

    if (![_persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error]) {

        /*

         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.

         Typical reasons for an error here include:

         * The persistent store is not accessible;

         * The schema for the persistent store is incompatible with current managed object model.

         Check the error message to determine what the actual problem was.

         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application’s resources directory instead of a writeable directory.

         If you encounter schema incompatibility errors during development, you can reduce their frequency by:

         * Simply deleting the existing store:

         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]

         * Performing automatic lightweight migration by passing the following dictionary as the options parameter:

         @{NSMigratePersistentStoresAutomaticallyOption:@YES, NSInferMappingModelAutomaticallyOption:@YES}

         Lightweight migration will only work for a limited set of schema changes; consult “Core Data Model Versioning and Data Migration Programming Guide” for details.

         */

        NSLog(@”Unresolved error %@, %@”, error, [error userInfo]);

        abort();

    }

    return _persistentStoreCoordinator;

}


5.NSManagedObjectContext : The NSManagedObjectContext object manages a collection of model objects, instances of the NSManagedObject class. It’s perfectly possible to have multiple managed object contexts. Each managed object context is backed by a persistent store coordinator.

You can see a managed object context as a workbench on which you work with your model objects. You load them, you manipulate them, and save them on that workbench. Loading and saving are mediated by the persistent store coordinator. You can have multiple workbenches, which is useful if your application is multithreaded, for example.

While a managed object model and persistent store coordinator can be shared across threads, managed object contexts should never be accessed from a thread different than the one they were created on. We’ll discuss multithreading in more detail later in this series.

– (NSManagedObjectContext *)managedObjectContext

{

    if (_managedObjectContext != nil) {

        return _managedObjectContext;

    }

    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];

    if (coordinator != nil) {

        _managedObjectContext = [[NSManagedObjectContext alloc] init];

        [_managedObjectContext setPersistentStoreCoordinator:coordinator];

    }

    return _managedObjectContext;

}

How to create framework in Xcode


1. Step 1 :: Create a Cocoa Touch Static Library

Go  Xcode—> New Project —> iOS —> Framework & Library —> Cocoa Touch Static Library —> Named you app .

Screen Shot 2015-05-14 at 2.04.37 PM

Step : 2 Delete .m File from app , Select Move to trash.

Screen Shot 2015-05-14 at 2.08.02 PM

Step 3 : Open AppHelper.h and delete all content . And add

#import <UIKit/UIKit.h>

Click Project Navigator –> Targets –> Builds phases –> Link Binary with Libraries –> Add UIKit framework.

Screen Shot 2015-05-14 at 2.12.47 PM

Step 4:  Click on Editer –> Add Build Phase –> Add Header Build phase

Screen Shot 2015-05-14 at 2.18.57 PM

Step 5 :: Drag n Drop AppHelper.h in Public header

Screen Shot 2015-05-14 at 3.14.27 PM

Step 6: Go to Build Setting and Search public header . Double click on the Public Headers Folder Path setting and enter the following in the popup:   include/$(PROJECT_NAME)

Screen Shot 2015-05-14 at 3.23.14 PM

Step 7: Create New class assume CommonCode , And write you code for which you want to make framework. and Import it in AppHelper.h. Also remember make CommonCode to public.

Screen Shot 2015-05-14 at 3.39.37 PM

Note :: You can add more class similar type but make sure , keep minimum class public.

Step 8::  Since you’re creating a framework for others to use, it’s best to disable both and let the user choose what’s best for their project. To do this, using the same search field as before, update the following settings:

  • Dead Code Stripping – Set this to NO
  • Strip Debug Symbols During Copy – Set this to NO for all configurations
  • Strip Style – Set this to Non-Global Symbols

Build and run. There’s not a lot to see yet, but it’s still good to confirm the project builds successfully and without warnings or errors.

To build, select the target as iOS Device and press cmd+B to perform the build. Once completed, the libAppHelper.a product in the Products group of the Project Navigator will turn from red to black, signaling that it now exists. Right click on libAppHelper.a and select Show in Finder.

Here You have created a static library But not Framework.

For creating Framework , You also need to follow some more Step.

There are a couple of things that make a framework distinct:

  1. The directory structure. Frameworks have a special directory structure that is recognized by Xcode. You’ll create a build task, which will create this structure for you.
  2. The Slices. Currently, when you build the library, it’s only for the currently required architecture, i.e. i386, arm7, etc. In order for a framework to be useful, it needs to include builds for all the architectures on which it needs to run. You’ll create a new product which will build the required architectures and place them in the framework.

Step 1:: Go to Editer –> Add Build phase –> Add Run Script Build Phase

Screen Shot 2015-05-14 at 3.34.19 PM

Step 2. Make double click to Rename it as named Build Framework  and

Paste the following Bash script into the script field:

set -e
 
export FRAMEWORK_LOCN="${BUILT_PRODUCTS_DIR}/${PRODUCT_NAME}.framework"
 
# Create the path to the real Headers die
mkdir -p "${FRAMEWORK_LOCN}/Versions/A/Headers"
 
# Create the required symlinks
/bin/ln -sfh A "${FRAMEWORK_LOCN}/Versions/Current"
/bin/ln -sfh Versions/Current/Headers "${FRAMEWORK_LOCN}/Headers"
/bin/ln -sfh "Versions/Current/${PRODUCT_NAME}" \
             "${FRAMEWORK_LOCN}/${PRODUCT_NAME}"
 
# Copy the public headers into the framework
/bin/cp -a "${TARGET_BUILD_DIR}/${PUBLIC_HEADERS_FOLDER_PATH}/" \
           "${FRAMEWORK_LOCN}/Versions/A/Headers"

Screen Shot 2015-05-14 at 3.39.37 PM

Step 3: Now, select the AppHelper static library scheme and the iOS Device build target, then build using cmd+B.

Right click on the libAppHelper.a static library  and once again select Show In Finder.

Your Framework is ready to use Now


Best Of Luck

Sunny Singh

Lineage Technology

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

Open Preview editor in Xcode 6


Open Preview editor in Xcode 6

Screen Shot 2015-03-30 at 5.59.43 PM

If you want know how your screen will look in all iOS device . Preview editor is a better option. To open Preview editor  go following step.

  1. In the Project Navigator pane, single-click a storyboard/XIB file to open it in the main Xcode window.
  2. Now double-click that same file to open it in a new window.
  3. Move the new window to another monitor and maximize it.
  4. Click on the new window to make sure it has input focus, then typeOption+Command+Enter to open an assistant editor in that window.
  5. In the assistant editor’s jump bar click on ‘Automatic‘ to open the drop-down menu (see the screenshot below if you don’t know what this means).
  6. Click on the ‘Preview‘ menu item to open the preview editor.
  7. Click and hold next to the assistant editor’s jump bar, then drag up or left (depending on which editor layout you prefer; vertical or horizontal), to maximize the preview’s screen real estate.

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)

        })

2014 in review


The WordPress.com stats helper monkeys prepared a 2014 annual report for this blog.

Here’s an excerpt:

The concert hall at the Sydney Opera House holds 2,700 people. This blog was viewed about 16,000 times in 2014. If it were a concert at Sydney Opera House, it would take about 6 sold-out performances for that many people to see it.

Click here to see the complete report.