Sunday, May 25, 2014

NSUserDefaults Security Issue - iOS



Some developers don’t prefer to save data in the Keychain because it is not that straightforward to implement . However, saving info in the Keychain is probably the most secure way of storing data on a non-jailbroken device. Basically, the code for saving data in the keychain is just like saving data with NSUserDefaults with this wrapper. Here is a snippet of code that saves a string to the keychain. Notice that the syntax looks very similar to using NSUserDefaults.


1
2
PDKeychainBindings *bindings = [PDKeychainBindings sharedKeychainBindings];
[bindings setObject:@"XYZ" forKey:@"authToken"];
And here is a small snippet for fetching data from the keychain.
1
2
PDKeychainBindings *bindings = [PDKeychainBindings sharedKeychainBindings];
NSLog(@"Auth token is %@",[bindings objectForKey:@"authToken"]]);


Tuesday, May 20, 2014

Predicate Format String Syntax

The parser string is different from a string expression passed to the regex engine. This article describes the parser text, not the syntax for the regex engine.

Parser Basics

The predicate string parser is whitespace insensitive, case insensitive with respect to keywords, and supports nested parenthetical expressions. The parser does not perform semantic type checking.
Variables are denoted with a $ (for example $VARIABLE_NAME). ? is not a valid parser token.
The format string supports printf-style format arguments such as %x (see “Formatting String Objects”). Two important arguments are %@ and %K.
  • %@ is a var arg substitution for an object value—often a string, number, or date.
  • %K is a var arg substitution for a key path.
When string variables are substituted into a format string using %@ , they are surrounded by quotation marks. If you want to specify a dynamic property name, use %K in the format string, as shown in the following example.
NSString *attributeName = @"firstName";
NSString *attributeValue = @"Adam";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like %@",
        attributeName, attributeValue];
The predicate format string in this case evaluates to firstName like "Adam".
Single or double quoting variables (or substitution variable strings) cause %@%K, or $variable to be interpreted as a literal in the format string and so prevent any substitution. In the following example, the predicate format string evaluates to firstName like "%@" (note the single quotes around %@).
NSString *attributeName = @"firstName";
NSString *attributeValue = @"Adam";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"%K like '%@'",
        attributeName, attributeValue];

Basic Comparisons

===
The left-hand expression is equal to the right-hand expression.
>==>
The left-hand expression is greater than or equal to the right-hand expression.
<==<
The left-hand expression is less than or equal to the right-hand expression.
>
The left-hand expression is greater than the right-hand expression.
<
The left-hand expression is less than the right-hand expression.
!=<>
The left-hand expression is not equal to the right-hand expression.
BETWEEN
The left-hand expression is between, or equal to either of, the values specified in the right-hand side.
The right-hand side is a two value array (an array is required to specify order) giving upper and lower bounds. For example, 1 BETWEEN { 0 , 33 }, or $INPUT BETWEEN { $LOWER, $UPPER }.
In Objective-C, you could create a BETWEEN predicate as shown in the following example:
NSPredicate *betweenPredicate =
    [NSPredicate predicateWithFormat: @"attributeName BETWEEN %@", @[@1, @10]];
This creates a predicate that matches ( ( 1 <= attributeValue ) && ( attributeValue <= 10 ) ), as illustrated in the following example:
NSPredicate *betweenPredicate =
    [NSPredicate predicateWithFormat: @"attributeName BETWEEN %@", @[@1, @10]];
 
NSDictionary *dictionary = @{ @"attributeName" : @5 };
 
BOOL between = [betweenPredicate evaluateWithObject:dictionary];
if (between) {
    NSLog(@"between");
}

Boolean Value Predicates

TRUEPREDICATE
A predicate that always evaluates to TRUE.
FALSEPREDICATE
A predicate that always evaluates to FALSE.

Basic Compound Predicates

AND&&
Logical AND.
OR||
Logical OR.
NOT!
Logical NOT.

String Comparisons

String comparisons are by default case and diacritic sensitive. You can modify an operator using the key characters cand d within square braces to specify case and diacritic insensitivity respectively, for example firstName BEGINSWITH[cd] $FIRST_NAME.
BEGINSWITH
The left-hand expression begins with the right-hand expression.
CONTAINS
The left-hand expression contains the right-hand expression.
ENDSWITH
The left-hand expression ends with the right-hand expression.
LIKE
The left hand expression equals the right-hand expression: ? and * are allowed as wildcard characters, where ?matches 1 character and * matches 0 or more characters.
MATCHES
The left hand expression equals the right hand expression using a regex-style comparison according to ICU v3 (for more details see the ICU User Guide for Regular Expressions).

Aggregate Operations

ANYSOME
Specifies any of the elements in the following expression. For example ANY children.age < 18.
ALL
Specifies all of the elements in the following expression. For example ALL children.age < 18.
NONE
Specifies none of the elements in the following expression. For example, NONE children.age < 18. This is logically equivalent to NOT (ANY ...).
IN
Equivalent to an SQL IN operation, the left-hand side must appear in the collection specified by the right-hand side.
For example, name IN { 'Ben', 'Melissa', 'Nick' }. The collection may be an array, a set, or a dictionary—in the case of a dictionary, its values are used.
In Objective-C, you could create a IN predicate as shown in the following example:
NSPredicate *inPredicate =
            [NSPredicate predicateWithFormat: @"attribute IN %@", aCollection];
where aCollection may be an instance of NSArrayNSSetNSDictionary, or of any of the corresponding mutable classes.
array[index]
Specifies the element at the specified index in the array array.
array[FIRST]
Specifies the first element in the array array.
array[LAST]
Specifies the last element in the array array.
array[SIZE]
Specifies the size of the array array.

Identifiers

C style identifier
Any C style identifier that is not a reserved word.
#symbol
Used to escape a reserved word into a user identifier.
[\]{octaldigit}{3}
Used to escape an octal number ( \ followed by 3 octal digits).
[\][xX]{hexdigit}{2}
Used to escape a hex number ( \x or \X followed by 2 hex digits).
[\][uU]{hexdigit}{4}
Used to escape a Unicode number ( \u or \U followed by 4 hex digits).


Literals

Single and double quotes produce the same result, but they do not terminate each other. For example, "abc" and'abc' are identical, whereas "a'b'c" is equivalent to a space-separated concatenation of a'b'c.
FALSENO
Logical false.
TRUEYES
Logical true.
NULLNIL
A null value.
SELF
Represents the object being evaluated.
"text"
A character string.
'text'
A character string.
Comma-separated literal array
For example, { 'comma', 'separated', 'literal', 'array' }.
Standard integer and fixed-point notations
For example, 1272.7182819.75.
Floating-point notation with exponentiation
For example, 9.2e-5.
0x
Prefix used to denote a hexadecimal digit sequence.
0o
Prefix used to denote an octal digit sequence.
0b
Prefix used to denote a binary digit sequence.

Updating values - Core Data

Procedure

1. Create context object

 AppDelegate *app=[[UIApplication sharedApplication]delegate];

    NSManagedObjectContext *Obj=[app managedObjectContext];

2. Create Fetch request 

 NSFetchRequest * request = [[NSFetchRequest alloc] init];

    [request setEntity:[NSEntityDescription entityForName:@"Stations" inManagedObjectContext:Obj]];

    [request setPredicate:[NSPredicate predicateWithFormat:@"name ==%@",@"Sample string"]];
    
    
3. Execute request  and save the result in managed object (aBook is managed object class)
   
    aBook = [[Obj executeFetchRequest:request error:&error2] lastObject];

4. Check for error

 if (error2) {
        //Handle any errors
    }
    
    if (!aBook) {
        //Nothing there to update
    }
    

5. Update value and saving 

   
    aBook.name = @"BarBar";
    
    //Save it
    error2 = nil;
    if (![Obj save:&error2]) {
        //Handle any error with the saving of the context
    }

Reading / retrieving values from core data

Procedures


1. Create NSFetchRequest object


          NSFetchRequest *request=[[NSFetchRequest alloc]init];

2. Create NSEntityDescription object using entity name and NSManagedObjectcontext

       NSEntityDescription *entity=[NSEntityDescription entityForName:@"Stations"         inManagedObjectContext:Obj];

3. Set Entity to request

[request setEntity:entity];

4. Create NSSortDescriptor object for setting tags

 NSSortDescriptor *des=[[NSSortDescriptor alloc]initWithKey:@"name" ascending:NO];

    NSArray *arrDes=[[NSArray alloc]initWithObjects:des, nil];

5. Set Descriptor to request
    
        [request setSortDescriptors:arrDes];

6. Use Predicate for filter-out the values from core data

 NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name == %@", @"wwww"];
    [request setPredicate:predicate];

7. Fetch data / Execute the request

Stations * aBook = nil;
 aBook = [[Obj executeFetchRequest:request error:&error2] lastObject];



Inserting Value to Core Data

Procedure


1. Create NSManagedObjectContext Object

    AppDelegate *app=[[UIApplication sharedApplication]delegate];

    NSManagedObjectContext *Obj=[app managedObjectContext];

2. Create NSManagedObjectModel object using NSManagedObjectContext

 NSManagedObjectModel *newContact= [NSEntityDescription
                  insertNewObjectForEntityForName:@"Stations"
                  inManagedObjectContext:Obj];

    [newContact setValue:@"Value1" forKey:@"name"];
    [newContact setValue:@"value2" forKey:@"zipcode"];

3. Create Object for Error
     
                                              NSError *error;

4. Save NSManagedObjectContext

                                             [Obj save:&error];

Monday, May 12, 2014

iOS 7.1 App Life Cycle

Launching an app into the foreground





Launching an app into the background 


iOS regulates background processing very tightly, and offers three approaches to implement it:
  • Register a Background Task - If an application needs to complete an important task, it can ask iOS not to interrupt the task when the application moves into the background. For example, an application might need to finish logging in a user, or finish downloading a large file.
  • Register as a Background-Necessary Application - An app can register as a specific type of application that has known, specific backgrounding requirements, such as AudioVoIPExternal Accessory,Newsstand, and Location. These applications are allowed continuous background processing privileges as long as they are performing tasks that are within the parameters of the registered application type.
  • Enable Background Updates - Applications can trigger background updates with Region Monitoring or by listening for Significant Location Changes. As of iOS 7, applications can also register to update content in the background using Background Fetch or Remote Notifications.



Change of App State in iOS 






The App Launch Sequence on iOS

In the beginning was main()

The execution of every C program starts with a function called main(), and since Objective-C is a strict superset of C, the same must be true for an Objective-C program. If you create a new iOS project from one of the default templates, Xcode places this function in a separate file called main.m in the Supporting Filesgroup. Usually, you never have to look at that file but let’s do. This is the entire code of main():
1
2
3
4
5
6
7
int main(int argc, char *argv[])
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    int retVal = UIApplicationMain(argc, argv, nil, nil);
    [pool release];
    return retVal;
}
The function’s arguments argc and argv contain info about the command-line arguments passed to the executable on launch. We can safely ignore them for this discussion. Let’s have a look at what the function does, which seems to be very litte:
  1. It creates an autorelease pool because in every Cocoa app one must exist at all times (otherwise, anautorelease call would fail).
  2. It calls a function named UIApplicationMain(). We will take a deeper look at it below.
  3. It drains the autorelease pool it just created.
  4. It returns the return value of UIApplicationMain() to its caller (which is the shell that launched the executable).
When an (Objective-)C program reaches the end of main(), it ends. So this looks like a very short program indeed. Nevertheless, this is how all iOS apps work, so the secret must be the UIApplicationMain()function. Should it ever return, our program would end immediately.

UIApplicationMain()

Looking at the documentation for UIApplicationMain(), we find this:
This function instantiates the application object from the principal class and and instantiates the delegate (if any) from the given class and sets the delegate for the application. It also sets up the main event loop, including the application’s run loop, and begins processing events. If the application’s Info.plist file specifies a main nib file to be loaded, by including theNSMainNibFile key and a valid nib file name for the value, this function loads that nib file.
Despite the declared return type, this function never returns.
Let’s take this apart step by step:
App Launch Sequence on iOS 4
Flowchart of the app launch sequence on iOS 4. Feel free to share this image under a Creative Commons Attribution license (CC-BY).
  1. First, the function creates the main application object (step 3 in the flowchart). If you specify nil as the third argument to UIApplicationMain() (the default), it will create an instance of UIApplication in this step. This is usually what you want. However, if you need to subclass UIApplication (for example, to override its event handling in sendEvent:), you have to pass a string with the name of your subclass to UIApplicationMain().
  2. The function then looks at its fourth argument. If it is non-nil, it interprets it as the name of the class for the application delegate, instantiates an object of this class and assigns it as the application object’sdelegate. The default for the fourth argument is nil, though, which signifies that the app delegate will be created in the main NIB file.
  3. Next, UIApplicationMain() loads and parses your app’s Info.plist (step 4). If it contains a key named “Main nib file base name” (NSMainNibFile), the function will also load the NIB file specified there (step 5).
  4. By default, the main NIB file is called MainWindow.nib. It contains at least an object representing the application delegate, connected to the File’s Owner’s delegate outlet (step 6), and a UIWindow object that will be used as the app’s main window, connected to an outlet of the app delegate. If you used a view-controller-based app template, the NIB file will also contain your app’s root view controller and possibly one or more view child controllers.
    It is worth mentioning that this is the only step where the UIKit-based app templates (Window-based, View-based, Navigation-based, Tab-based, etc.) differ significantly from each other. If you started out with a view-based app and later want to introduce a navigation controller, there is no need to start a new project: simply replace the root view controller in the main NIB file and adjust one or two lines of code in the app delegate. I noticed that many newbies to the iOS platform struggle with this problem and assume a huge difference between the different project templates. There isn’t.
  5. Now, UIApplicationMain() creates the application’s run loop that is used by the UIApplicationinstance to process events such as touches or network events (step 7). The run loop is basically an infinite loop that causes UIApplicationMain() to never return.
  6. Before the application object processes the first event, it finally sends the well-knownapplication:didFinishLaunchingWithOptions: message to its delegate, giving us the chance to do our own setup (step 8). The least we have to do here is put our main window on the screen by sending it a makeKeyAndVisible message.

Entry points

You see, there is no magic here. Besides application:didFinishLaunchingWithOptions:, there are several more entry points for custom code during the launch sequence (none of which are usually needed):
  • Directly in main() before UIApplicationMain() is called.
  • The init method of a custom UIApplication subclass.
  • The initWithCoder: or awakeFromNib methods of our application delegate if it is created from a NIB file (the default).
  • The +initialize methods of our application delegate class or a custom UIApplication subclass. Any class receives an +initialize message before it is sent its first message from within the program.
Note that this sequence only happens at the actual launch of an app. If the app is already running and simply brought back from the background, none of this occurs.

Regards or Taken from : http://oleb.net/blog