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

Strava integration in iOS


Strava is a website and  mobile app used to track athletic activity via GPS. Its headquarters are located in California. The most popular activities tracked using the software are  Cycling and running.

If we are developing a health based application , sometimes we need to fetch data from Strava for analysis .In this tutorial , we will show you how to fetch data from Strava.

Strava provide full API to fetch data from their server . for more detail https://strava.github.io/api/v3/oauth/ .

  1. Strava API work with Oauth 2.0 , go through https://www.strava.com/login and register your app and get ClientId , Client Secret .
  2. Download OAuth library from  https://github.com/OAuthSwift/OAuthSwift
  3. Download demo STRAVA app from https://github.com/msyshani/StravaDemo-for-iOS

 

Thanks

Enjoy coding

 

 


					

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

}

How to create .pem for apple push notification


cropped-mobile.jpg

To enable Push Notification for your iOS app, we will need you to create and upload the Apple Push Notification Certificate (.pem file) to us so we will be able to connect to Apple Push Server on your behalf.

Step 1: Login to iOS Provisioning Portal, click “Certificates” on the left navigation bar. Then, click “+” button.

enter image description here

Step 2: Select Apple Push Notification service SSL (Production) option under Distribution section, then click “Continue” button.

enter image description here

Step 3: Select the App ID you want to use for your BYO app (How to Create An App ID), then click “Continue” to go to next step.

enter image description here

Step 4: Follow the steps “About Creating a Certificate Signing Request (CSR)” to create a Certificate Signing Request.

enter image description here

To supplement the instruction provided by Apple. Here are some of the additional screenshots to assist you to complete the required steps:

Step 4 Supplementary Screenshot 1: Navigate to Certificate Assistant of Keychain Access on your Mac.

enter image description here

Step 4 Supplementary Screenshot 2: Fill in the Certificate Information. Click Continue.

enter image description here

Step 5: Upload the “.certSigningRequest” file which is generated in Step 4, then click “Generate” button.

enter image description here

Step 6: Click “Done” to finish the registration, the iOS Provisioning Portal Page will be refreshed that looks like the following screen:

enter image description here

Then Click “Download” button to download the certificate (.cer file) you’ve created just now. – Double click the downloaded file to install the certificate into Keychain Access on your Mac.

Step 7: On your Mac, go to “Keychain”, look for the certificate you have just installed. If unsure which certificate is the correct one, it should start with “Apple Production IOS Push Services:” followed by your app’s bundle ID.

enter image description here

Step 8: Expand the certificate, you should see the private key with either your name or your company name. Select both items by using the “Select” key on your keyboard, right click (or cmd-click if you use a single button mouse), choose “Export 2 items”, like Below:

enter image description here

Then save the p12 file with name “pushcert.p12” to your Desktop – now you will be prompted to enter a password to protect it, you can either click Enter to skip the password or enter a password you desire.

Step 9: Now the most difficult part – open “Terminal” on your Mac, and run the following commands:

cd
cd Desktop
openssl pkcs12 -in pushcert.p12 -out pushcert.pem -nodes -clcerts

Step 10: Remove pushcert.p12 from Desktop to avoid mis-uploading it to Build Your Own area. Open “Terminal” on your Mac, and run the following commands:

cd
cd Desktop
rm pushcert.p12

Now you have successfully created an Apple Push Notification Certificate (.pem file)! You will need to upload this file to our Build Your Own area later on. 🙂

Oops concept in objective C


Apple has documented a best illustration on Opps concept which is  base of Objective C  .

You can checkout and learn how Opps concept is using in Objective C

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/OOP_ObjC/Articles/ooObjectModel.html#//apple_ref/doc/uid/TP40005149-CH5-SW6

Continue reading

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;

}

Touch ID Authentication in iOS App


Step 1: Add Local Authentication framework to you Application

Step 2: Import

#import <LocalAuthentication/LocalAuthentication.h> in your class

Step 3: Write code for Touch Authentication.

– (IBAction)MakeTouchIdAthentication:(id)sender {

    LAContext *context = [[LAContext alloc] init];

    

    NSError *error = nil;

    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error]) {

        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics

                localizedReason:@”Aunthenticate with Touch ID”

                          reply:^(BOOL success, NSError *error) {

                              

                              if (error) {

                                  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Error”

                                                                                  message:@”Oppps , Some error in Athenticationg.”

                                                                                 delegate:nil

                                                                        cancelButtonTitle:@”Ok”

                                                                        otherButtonTitles:nil];

                                  [alert show];

                                  return;

                              }

                              

                              if (success) {

                                  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Success”

                                                                                  message:@”Successful Athentication.”

                                                                                 delegate:nil

                                                                        cancelButtonTitle:@”Ok”

                                                                        otherButtonTitles:nil];

                                  [alert show];

                                  

                              } else {

                                  UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Error”

                                                                                  message:@”You are not the device owner.”

                                                                                 delegate:nil

                                                                        cancelButtonTitle:@”Ok”

                                                                        otherButtonTitles:nil];

                                  [alert show];

                              }

                              

                          }];

        

    } else {

        

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Error”

                                                        message:@”Your device cannot authenticate using TouchID.”

                                                       delegate:nil

                                              cancelButtonTitle:@”Ok”

                                              otherButtonTitles:nil];

        [alert show];

        

    }

}

Step 4. Call this function from UIButton.

iOS Simulator Screen Shot May 14, 2015, 4.59.42 PM

Best Of Luck

Sunny Singh

Lineage Technology

Skype: lineagetechnology

Twitter: lineageApps

Facebook: https://www.facebook.com/Lineagetechnology

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

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

How to add provision certificate in Xcode


To develop and deploy the provider side of a client/server app, you must get SSL certificates from Member Center. Each certificate is limited to a single app, identified by its bundle ID. Each certificate is also limited to one of two development environments, each with its own assigned hostname:

  • Development: Use the development environment for initial development and testing of the provider app. It provides the same set of services as the production environment, although with a smaller number of server units. The development environment also acts as a virtual device, enabling simulated end-to-end testing.You access the development environment at gateway.sandbox.push.apple.com, outbound TCP port 2195.
  • Production: Use the production environment when building the production version of the provider app. Apps using the production environment must meet Apple’s reliability requirements.You access the production environment at gateway.push.apple.com, outbound TCP port 2195.

Step to add profile in Your app is following

1. Double Tap on provision certificates . it will be added in xcode.

2. Open Your app in Xcode and click at project name , top in project navigator.

Screen Shot 2015-03-30 at 5.50.19 PM

2.  Select Target and then click on Build setting.

Screen Shot 2015-03-30 at 5.50.49 PM

3. Search “Code Sign” in build setting. and select your provisional certificate from list of provisional certificates in Provisional profile . and select your Distribution or development certificate in “Code signing identity”.

Screen Shot 2015-03-30 at 5.53.28 PM

4. Now select Project in left side and repeat same process again for Project.

Screen Shot 2015-03-30 at 5.51.41 PM

Best of Luck………

Enjoy coding…….