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

Few moment with Android


1. Android Core Building Blocks                                                

An android component is simply a piece of code that has a well defined life cycle e.g. Activity, Receiver, Service etc.

(i) Activity : An activity is a class that represents a single screen. It is like a Frame in AWT.

(ii) View: A view is the UI element such as button, label, text field etc. Anything that you see is a view.

(iii) Intent ::

Intent is used to invoke components. It is mainly used to:

  • Start the service
  • Launch an activity
  • Display a web page
  • Display a list of contacts
  • Broadcast a message
  • Dial a phone call etc.

For example, you may write the following code to view the webpage.

// Implicit Intent by specifying a URI

Intent i = new Intent(Intent.ACTION_VIEW,

Uri.parse(http://www.example.com”));

// Starts Implicit Activity

startActivity(i);

// Explicit Intent

  1. Intent i = new Intent(getApplicationContext(), ActivityTwo.class);
  2.  startActivity(i);

(iv) Service: Service is a background process that can run for a long time.

There are two types of services local and remote. Local service is accessed from within the application whereas remote service is accessed remotely from other applications running on the same device.

(v) Content Provider : Content Providers are used to share data between the applications.

(vi) Fragment : Fragments are like parts of activity. An activity can display one or more fragments on the screen at the same time.

(vi) AndroidManifest.xml : The AndroidManifest.xml file contains information of your package, including components of the application such as activities, services, broadcast receivers, content providers etc.

It performs some other tasks also:

  • It is responsible to protect the application to access any protected parts by providing the permissions.
  • It also declares the android api that the application is going to use.
  • It lists the instrumentation classes. The instrumentation classes provides profiling and other informations. These informations are removed just before the application is published etc.

This is the required xml file for all the android application and located inside the root directory.

(vii) Android R.java file : Android R.java is an auto-generated file by aapt (Android Asset Packaging Tool) that contains resource IDs for all the resources of res/ directory.

If you create any component in the activity_main.xml file, id for the corresponding component is automatically created in this file. This id can be used in the activity source file to perform any action on the component.

(viii) Android Hide Title Bar Example : The requestWindowFeature(Window.FEATURE_NO_TITLE) method of Activity must be called to hide the title. But, it must be coded before the setContentView method.

  1.    @Override
  2.     protected void onCreate(Bundle savedInstanceState) {
  3.         super.onCreate(savedInstanceState);
  4.         requestWindowFeature(Window.FEATURE_NO_TITLE);//will hide the title not the title bar
  5.         setContentView(R.layout.activity_main);
  6.     }
  7. }

The setFlags() method of Window class is used to display content in full screen mode. You need to pass theWindowManager.LayoutParams.FLAG_FULLSCREEN constant in the setFlags method.

  1. @Override  
  2. protected void onCreate(Bundle savedInstanceState) {
  3.     super.onCreate(savedInstanceState);
  4.     requestWindowFeature(Window.FEATURE_NO_TITLE);
  5.     //code that displays the content in full screen mode  
  6.     this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  7.                 WindowManager.LayoutParams.FLAG_FULLSCREEN);//int flag, int mask
  8.     setContentView(R.layout.activity_main);
  9. }

(ix) ArrayAdapter : A concrete BaseAdapter that is backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

To use something other than TextViews for the array display, for instance, ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.

(x) Android Activity Lifecycle : Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The android Activity is the subclass of ContextThemeWrapper class.

An activity is the single screen in android. It is like window or frame of Java.

By the help of activity, you can place all your UI components or widgets in a single screen.

The 7 lifecycle method of Activity describes how activity will behave at different states.

Let’s see the 7 lifecycle methods of android activity.

Method

Description

onCreate

called when activity is first created.

onStart

called when activity is becoming visible to the user.

onResume

called when activity will start interacting with the user.

onPause

called when activity is not visible to the user.

onStop

called when activity is no longer visible to the user.

onRestart

called after your activity is stopped, prior to start.

onDestroy

called before the activity is destroyed.

  1. package com.example.activitylifecycle;

  2. import android.os.Bundle;

  3. import android.app.Activity;

  4. import android.util.Log;

  5. import android.view.Menu;

  6. public class MainActivity extends Activity {

  7.     @Override

  8.     protected void onCreate(Bundle savedInstanceState) {

  9.         super.onCreate(savedInstanceState);

  10.         setContentView(R.layout.activity_main);

  11.         Log.d(“lifecycle”,“onCreate invoked”);  

  12.     }

  13.     @Override

  14.     protected void onStart() {

  15.         super.onStart();

  16.          Log.d(“lifecycle”,“onStart invoked”);  

  17.     }

  18.     @Override

  19.     protected void onResume() {

  20.         super.onResume();

  21.          Log.d(“lifecycle”,“onResume invoked”);  

  22.     }

  23.     @Override

  24.     protected void onPause() {

  25.         super.onPause();

  26.          Log.d(“lifecycle”,“onPause invoked”);  

  27.     }

  28.     @Override

  29.     protected void onStop() {

  30.         super.onStop();

  31.          Log.d(“lifecycle”,“onStop invoked”);  

  32.     }

  33.        @Override

  34.     protected void onRestart() {

  35.         super.onRestart();

  36.          Log.d(“lifecycle”,“onRestart invoked”);  

  37.     }

  38.     @Override

  39.     protected void onDestroy() {

  40.         super.onDestroy();

  41.          Log.d(“lifecycle”,“onDestroy invoked”);  

  42.     }

  43. }

2) Who is the founder of Android?

Andy Rubin.

3) What are the code names of android?

  1. Aestro
  2. Blender
  3. Cupcake
  4. Donut
  5. Eclair
  6. Froyo
  7. Gingerbread
  8. Honycomb
  9. Ice Cream Sandwitch
  10. Jelly Bean
  11. Kitkat

4) What are the advantages of android?

Open-source: It means no licence, distribution and development fee.

Platform-independent: It supports windows, mac and linux platforms.

Supports various technologies: It supports camera, bluetooth, wifi, speech, EDGE etc. technologies.

Highly optimized Virtual Machine: Android uses highly optimized virtual machine for mobile devices, called DVM (Dalvik Virtual Machine).

5) Does android support other language than java?

Yes, android app can be developed in C/C++ also using android NDK (Native Development Kit). It makes the performance faster. It should be used with android SDK.

6) What are the core building blocks of android?

The core building blocks of android are:

  • Activity
  • View
  • Intent
  • Service
  • Content Provider
  • Fragment etc.

7) What is the name of database used in android?

SQLite: An opensource and lightweight relational database for mobile devices.

8) What is AAPT?

AAPT is an acronym for android asset packaging tool. It handles the packaging process.

9) What is ADB?

ADB stands for Android Debug Bridge. It is a command line tool that is used to communicate with the emulator instance.

10) What is NDK?

NDK stands for Native Development Kit. By using NDK, you can develop a part of app using native language such as C/C++ to boost the performance.

Expert Level Question                                                                                                          

1. What is the relationship between the life cycle of an AsyncTask and an Activity? What problems can this result in? How can these problems be avoided?

Answer:: An AsyncTask is not tied to the life cycle of the Activity that contains it. So, for example, if you start an AsyncTask inside an Activity and the user rotates the device, the Activity will be destroyed (and a new Activity instance will be created) but the AsyncTask will not die but instead goes on living until it completes.

Then, when the AsyncTask does complete, rather than updating the UI of the new Activity, it updates the former instance of the Activity (i.e., the one in which it was created but that is not displayed anymore!). This can lead to an Exception (of the type java.lang.IllegalArgumentException: View not attached to window manager if you use, for instance, findViewById to retrieve a view inside the Activity).

There’s also the potential for this to result in a memory leak since the AsyncTask maintains a reference to the Activty, which prevents the Activity from being garbage collected as long as the AsyncTask remains alive.

For these reasons, using AsyncTasks for long-running background tasks is generally a bad idea . Rather, for long-runningbackground tasks, a different mechanism (such as a service) should be employed.

2. There are four Java classes related to the use of sensors on the Android platform. List them and explain the purpose of each.

Answer :: The four Java classes related to the use of sensors on the Android platform areL

  • Sensor: Provides methods to identify which capabilities are available for a specific sensor.
  • SensorManager: Provides methods for registering sensor event listeners and calibrating sensors.
  • SensorEvent: Provides raw sensor data, including information regarding accuracy.
  • SensorEventListener: Interface that defines callback methods that will receive sensor event notifications.

3.What is DDMS? Describe some of its capabilities.

Answer : DDMS is the Dalvik Debug Monitor Server that ships with Android. It provides a wide array of debugging features including:

  • port-forwarding services
  • screen capture
  • thread and heap information
  • network traffic tracking
  • incoming call and SMS spoofing
  • simulating network state, speed, and latency
  • location data spoofing

4. What is Dalvik Virtual Machine?

The name of Android’s virtual machine. The Dalvik VM is an interpreter-only virtual machine that executes files in the Dalvik Executable (.dex) format, a format that is optimized for efficient storage and memory-mappable execution. The virtual machine is register-based, and it can run classes compiled by a Java language compiler that have been transformed into its native format using the included “dx” tool. The VM runs on top of Posix-compliant operating systems, which it relies on for underlying functionality (such as threading and low level memory management). The Dalvik core class library is intended to provide a familiar development base for those used to programming with Java Standard Edition, but it is geared specifically to the needs of a small mobile device.

5. What is Android Runtime?

Android includes a set of core libraries that provides most of the functionality available in the core libraries of the Java programming language. Every Android application runs in its own process, with its own instance of the Dalvik virtual machine. Dalvik has been written so that a device can run multiple VMs efficiently. The Dalvik VM executes files in the Dalvik Executable (.dex) format which is optimized for minimal memory footprint. The VM is register-based, and runs classes compiled by a Java language compiler that have been transformed into the .dex format by the included “dx” tool.

6. What is the Open Handset Alliance?

The OHA is a consortium of 84 technology and mobile companies that have joined hands to accelerate innovation in mobile technology and at the same time offer the end users a better, cost-effective and richer mobile experience. Members of this include Google, HTC, Sony, Dell, Intel, Motorola, Qualcomm, Texas Instruments, Samsung, LG, T-Mobile, Nvidia. The OHA was started on 5 November 2007 by Google and 34 other companies. Android is the main software of the alliance.

7. What is the difference between Service and Thread?

Service is like an Activity but has no interface. Probably if you want to fetch the weather for example you won’t create a blank activity for it, for this you will use a Service. It is also known as Background Service because it performs tasks in background. A Thread is a concurrent unit of execution. You need to know that you cannot update UI from a Thread. You need to use a Handler for this.

8.What is the importance of XML-based layouts?

The use of XML-based layouts provides a consistent and somewhat standard means of setting GUI definition format. In common practice, layout details are placed in XML files while other items are placed in source files.

9. What are the steps in creating a bounded service through AIDL.

1. create the .aidl file, which defines the programming interface

2. implement the interface, which involves extending the inner abstract Stub class as well as implanting its methods.

3. expose the interface, which involves implementing the service to the clients.

10. What data types are supported by AIDL?

AIDL has support for the following data types:

string

charSequence

List

Map

all native Java data types like int, long, char and Boolean

11.What is the difference between a regular bitmap and a nine-patch image?

In general, a Nine-patch image allows resizing that can be used as background or other image size requirements for the target device. The Nine-patch refers to the way you can resize the image: 4 corners that are unscaled, 4 edges that are scaled in 1 axis, and the middle one that can be scaled into both axes.

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

Get Rs.10 cashback on recharges of Rs.50 & above.


PayTm on Android:: https://play.google.com/store/apps/details?id=net.one97.paytm&hl=en

Get Rs.10 cashback on recharges of Rs.50 & above. Use Code: APPCB50. Valid for 5 orders on Paytm App

Note:This code is applicable on Paytm Android,iOS & Windows Apps only

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

How to get UDID of your iOS device


There is two way to get UDID

  1. From iTune

2.From Xcode

1. From iTune You can get UDID using following step

  • Open itunes
  • You will get your device at right corner
  • Click on Summary tab and then double click on Identifier .then identifier will covert on UDID .

Screen Shot 2014-11-14 at 12.14.42 PM

Screen Shot 2014-11-14 at 12.15.04 PM

Screen Shot 2014-11-14 at 12.15.23 PM

  1. You can get UDID from Xcode using following steps

  • On Xcode menu, click on window and choose device.
  • select your device and your will your device’s UDID

Screen Shot 2014-11-14 at 12.44.38 PM

Screen Shot 2014-11-14 at 12.44.59 PM

Best of Luck

Lineage Technology , Lucknow India

http://www.lineagetechnology.com/

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

Use HexColor in Swift as a color


Add it in your class 

extension UIColor {

   convenience init(red: Int, green: Int, blue: Int) {

       assert(red >= 0 && red <= 255, “Invalid red component”)

       assert(green >= 0 && green <= 255, “Invalid green component”)

       assert(blue >= 0 && blue <= 255, “Invalid blue component”)

       self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0)

   }

   convenience init(netHex:Int) {

       self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff)

   }

}

Use it where you need…….

var color = UIColor(red: 0xFF, blue: 0xFF, green: 0xFF)

var color2 = UIColor(netHex:0xFFFFFF)

Lineage Technology


Lineage technology is a Mobile application based software company established in 2012. we are the fastest growing company in lucknow . We offer mobile application ( iOS , Android , BlackBerry ) development with Quality in affordable cast . Our motive is to attain client faith on us. Customer satisfaction is most important for us. we develop application in 6 step

      Step 1:: Analyze requirement .

      Step 2:: Discuss with Customer with Suggestion

      Step 3:: Develop in milestone.

      Step 4:: Application Testing

      Step 5:: Submit to server

      Step 6:: Customer Feedback

Key Area :: 

  • iOS app development
  • iPhone app development
  • iPad app development
  • Android app development
  • BlackBerry app development
  • Website development

Fore more detail Contact us :: msy.shani@gmail.com

                           Contact No:: +919935523781

                            website     ::  http://www.lineagetechnology.com/

Fotor01015113226