React-Native: Day by Day


Welcome to AppEngineer
We are come back with some exiting tutorial on React-native for iOS.

Why Choose React Native
At this point, you might think that React Native is another “write once, run anywhere” framework, like Titanium or PhoneGap, but you would be wrong. As Facebook very clearly states on their blog post, they acknowledge the differences between platforms, so instead, their goal is to bring the paradigms of React, which is very successful on the web, to native, while having the same set of engineers working on whatever platform they choose. They call this approach “learn once, write everywhere”.

How React Native actually works is by embedding the JavaScript files in the app, and running them locally. But also, one could have these files remotely on a server fetching their latest version when the app has connectivity. This would allow updating an application very rapidly, without having to go through the app store’s review process. There are also third party services that offer such solutions, and using them potentially could mean that for smaller applications that don’t have a lot of data to display (e.g. festival apps), a backend isn’t needed anymore.

Most of the coding is based on JavaScript and the paradigms in React. Thus, it makes more sense that a typical team working on a React Native application is composed mostly of JavaScript engineers, because ideally those will be already familiar with the tools and paradigms used by this framework: React, EcmaScript, Redux and Flex layout.

Advantages:
1. Learn once, write everywhere
2. Hot Reloading
3. Able to interact with Nativ code
4. Able to create libary that can used in both iOS and Android.
5. Save development cost (Up to 30%)
Limitations
1. Lack proper documentions
2. lack of developer community
3. Native SDK update
4. Uncertain roadmap

We are committed for Day by Day React-Native tutorial. You will get our first tutorial very soon.

Advertisements

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()

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.

Apple Shortens App Review : 2 days


Apple has cut the amount of time it takes to approve new submissions for the App Store down to just one day, claims a new report.

The initiative — which is part of Apple’s efforts to focus on improving its services at a time when iPhone sales are decreasing — means that, in the past year alone, the mean number of days it takes an app to be approved has fallen from 8.8 down to only 24 hours.

“A lot of the way that we build software for iOS is controlled around the fact that you have a one-week release cycle,” a developer who has done work for Uber and Foursquare told Bloomberg. “It can now happen within hours of submitting them, which is really awesome because it speeds up the development cycle.”

Slicing the approval time is one more way Apple can compete with Android, which doesn’t carry out extensive security or content checks on submitted apps before making them available on the Google Play store.

Phil Schiller took over running the App Store for Eddy Cue back in December. Since then, Apple has reduced its iAd advertising platforms, while moving over 100 employees to work on improving App Store search.

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. 🙂

How to create facebook album through iOS app


1.Requirement

i) facebook accessToken

2.Code

-(void)createFbAlbumwithName:(NSString *)AlbumName andId:(NSString *)bubbleId{

NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:@”fb_access_token”];

if(token==nil){

[self alertForfacebookAlbum:@”Your account not connected to facebook.” withActionTitle:@”Cancel”];

return;

}

NSMutableDictionary *paramsToCreateAlbum = [NSMutableDictionary dictionaryWithObjectsAndKeys:

                                               AlbumName, @”name”,

[NSString stringWithFormat:@”This album is created by YourApp app for Event ‘%@'”,AlbumName], @”message”,token,@”access_token”, nil];

[FBRequestConnection startWithGraphPath: @”me/albums”

parameters: paramsToCreateAlbum

HTTPMethod: @”POST”

completionHandler: ^(FBRequestConnection *connection,

id result,

NSError *error) {

if (!error) {

//publish content to albumID

NSLog(@”album key is %@”,[result objectForKey:@”id”]);

facebookAlbumId=[result objectForKey:@”id”];

//

}

else {

NSLog(@”error: %@”, error);

[self alertForfacebookAlbum:@”Error in creating facebook album” withActionTitle:@”Retry”];

}

                          }]; }

how to fetch all media from device using asset library


Hey use this methods to fetch video and photos from photo gallary in iOS 


-(void)getAllVideo

{

    [queue cancelAllOperations];

    queue = [[NSOperationQueue alloc] init];

    [queue addOperationWithBlock:^{

        //imageArray=[[NSArray alloc] init];

        mutableArray =[[NSMutableArray alloc]init];

        NSMutableArray* assetURLDictionaries = [[NSMutableArray alloc] init];

        library =[[ALAssetsLibrary alloc] init];

        void (^assetEnumerator)( ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {

            if(result != nil) {

                iff([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo]) {

                    

                     [assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];

                      NSURL *url= (NSURL*) [[result defaultRepresentation]url];

                    //NSLog(@”url is %@”,url);

                    NSDate *createdDate=[result valueForProperty:ALAssetPropertyDate];

                    NSMutableDictionary *dicValue=[[NSMutableDictionary alloc] init];

                    [dicValue setObject:[result valueForProperty:ALAssetPropertyDate]  forKey:@”media_created_time”];

                    [dicValue setObject:[NSString stringWithFormat:@”%@”,url]   forKey:@”media_url”];

                    [mutableArray addObject:dicValue];

                }

            }

        }else{

           

        }

   

     

     NSMutableArray *assetGroups = [[NSMutableArray alloc] init];

     void (^ assetGroupEnumerator) ( ALAssetsGroup *, BOOL *)= ^(ALAssetsGroup *group, BOOL *stop) {

         if(group != nil) {

             [group enumerateAssetsUsingBlock:assetEnumerator];

             [group setAssetsFilter:[ALAssetsFilter allVideos]];

             [assetGroups addObject:group];

             count=(int)[group numberOfAssets];

         }

     };

     assetGroups = [[NSMutableArray alloc] init];

     [library enumerateGroupsWithTypes:ALAssetsGroupAll

                            usingBlock:assetGroupEnumerator

                          failureBlock:^(NSError *error) {NSLog(@”There is an error”);}];

     }];

}


-(void)getAllPictures:(NSDictionary *)bubbleDic

{

    [queue cancelAllOperations];

    queue = [[NSOperationQueue alloc] init];

    

    [queue addOperationWithBlock:^{

        NSMutableArray* assetURLDictionaries = [[NSMutableArray alloc] init];

        library =[FetchFromDevice defaultAssetsLibrary];// [[ALAssetsLibrary alloc] init];

        void (^assetEnumerator)( ALAsset *, NSUInteger, BOOL *) = ^(ALAsset *result, NSUInteger index, BOOL *stop) {

            if(result != nil) {

                if([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {

                    

                    [assetURLDictionaries addObject:[result valueForProperty:ALAssetPropertyURLs]];

                      NSURL *url= (NSURL*) [[result defaultRepresentation]url];

                    //NSLog(@”url is %@”,url);

                    NSDate *createdDate=[result valueForProperty:ALAssetPropertyDate];

                    NSMutableDictionary *dicValue=[[NSMutableDictionary alloc] init];

                    [dicValue setObject:[result valueForProperty:ALAssetPropertyDate]  forKey:@”media_created_time”];

                    [dicValue setObject:[NSString stringWithFormat:@”%@”,url]   forKey:@”media_url”];

                    [mutableArray addObject:dicValue];

                    

                }

            }else{

                

                

            }

        };

        

        

        NSMutableArray *assetGroups = [[NSMutableArray alloc] init];

        

        void (^ assetGroupEnumerator) ( ALAssetsGroup *, BOOL *)= ^(ALAssetsGroup *group, BOOL *stop) {

            if(group != nil) {

                

                

                if ([[group valueForProperty:@”ALAssetsGroupPropertyType”] intValue] == ALAssetsGroupSavedPhotos)

                {

                    

                    [group enumerateAssetsUsingBlock:assetEnumerator];

                    [group setAssetsFilter:[ALAssetsFilter allPhotos]];

                    [assetGroups addObject:group];

                    count=(int)[group numberOfAssets];

                }

            }

        };

        

        assetGroups = [[NSMutableArray alloc] init];

        

        [library enumerateGroupsWithTypes:ALAssetsGroupSavedPhotos

                               usingBlock:assetGroupEnumerator

                             failureBlock:^(NSError *error) {NSLog(@”There is an error %@”,error);}];

        }];

}

2. how to fetch image from AlassetUrl

ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];

    NSString *imageStr=Your Url;

    [library assetForURL:[NSURL URLWithString:imageStr]

             resultBlock:^(ALAsset *asset) {

                 NSLog(@”fetchinging PHAssets…wwwwwwwwwwwwwww…………”);

                 

                 ALAssetRepresentation *rep = [asset defaultRepresentation];

                 @autoreleasepool {

                     CGImageRef iref = [rep fullScreenImage];

                     if (iref) {

                         UIImage *image = [UIImage imageWithCGImage:iref];

                     }

                 }

             }

            failureBlock:^(NSError *error){ NSLog(@”operation was not successfull!”);

            }];