iDev: UIImage and UIImage View

When we use images in our application then we face different type of scenarios while handling the image. Before we go into the scenarios / situations of image handling in Application, let us understand the concept of UIImage and UIImageView.

Concept of UIImage and UIImageView (container)

UIImage – Bitmap with different formats Ex png and jpeg. Recommended format is png.UIImageView – This is an iOS Widget that acts like a container for holding the image. To hold the image, UIImageView is required.

When UIImage is shown in UIImageView, there is a property (Content Mode) of UIImageView, that render the Image in UIImageView. We mostly use three types of Content Mode property. These are:

  • Scale To Fill
  • Aspect Fit
  • Aspect Fill

How these Content Mode render the image we can see by following examples

  • UIImage of size (100×150)
  • UIImageView of size (200×200)

Different Content modes for placing Image in ImageView

1. Scale To Fill

In this case, content is scaled to fill in ImageView with distorted or same aspect ratio. If the image aspect ratio is different than that of container then final image ratio when fitted in the container will be different and hence the image is finally distorted.

(Aspect Ratio is Width / Height)

InnovationM Image Handling in iOS

2. Aspect Fit

In this case, content is scaled to fit in ImageView (container) without changing the aspect ratio of image . Remainder is transparent.

InnovationM Image Handling in iOS

3. Aspect Fill Without Clipping

In this case, image is scaled to fill in ImageView. Aspect ratio of image is not changed.

InnovationM Image Handling in iOS

4. Aspect Fill With Clipping

In this case, content is scaled to fill in ImageView the same way it happen in the above case but then finally image is cropped to the exact size of the ImageView size.

InnovationM Image Handling in iOS

Calculating new width and height with maintaining aspect ratio

Image original width = 100 and height = 150
Container width  = 200 and height = 200

x-ratio = Container width / Image original width = 200/100 = 2.0
y-ratio =  Container height / Image original height = 200/ 150 =  1.33

Selected ratio = min (x-ratio, y-ratio) = 1.33

Final Image width = Image original width * Selected Ratio = 100 * 1.33 = 133
Final Image height = Image original height * Selected Ratio = 150 * 1.33 = 200

Final Image width x height = 133 x 200 (Original width x height of image was 100 x 150)

Showing Images coming from Server (Different Scenarios)

We can use Aspect Fit mode for all the scenarios. It will serve in every scenario if you don’t want to distort image.

Scenario 1
Image width is lesser than Container width.
Image height is lesser than Container height

Image width = 100 and height = 150
UIImageView width = 200 and height = 200

Final Image width = 133  and height = 200 (Refer the calculations above)
Image is scaled up to fit the container.

InnovationM Image Handling in iOS

Scenario 2 
Image width is greater than Container width.
Image height is lesser than Container height

Image width = 100 and height = 150
UIImageView width = 80 and height = 200

Final Image width = 80 and height = 122
Image is scaled down to fit the container.

InnovationM Image Handling in iOS

Scenario 3
Image width is lesser than Container width.
Image height is greater than Container height.

Image width = 100 and height = 150
UIImageView width = 200 and height = 120

Final width = 80  and height = 120
Image is scaled down to fit the container.
InnovationM Image Handling in iOS

Scenario 4
Image width is greater than Container width.
Image height is greater than Container height.

Image width = 100 and height = 150
UIImageView width = 80 and height = 100

Final width = 66  and height = 100
Image is scaled down to fit the container.

InnovationM Image Handling in iOS

Scenario 5 (Same Aspect Ratio of Image and ImageView)
Image width is greater than Container width.
Image height is greater than Container height.

Image width = 100 and height = 150
UIImageView width = 80 and height = 120

Final width = 80 and height = 120
Image is scaled down to fit the container.

InnovationM Image Handling in iOS

Scenario 6 (Same Aspect Ratio of Image and ImageView)
Image width is lesser than Container width.
Image height is lesser than Container height.

Image width = 100 and height = 150
UIImageView width = 120 and height = 180

Final width = 120 and height = 180
Image is scaled up to fit the container.

InnovationM Image Handling in iOS

How we change the image size and compress image file size-

Uploading Images to the Server (Different Scenarios)

Many times we have to upload images in an application from device (iPhone, iPad) to the server. It could be a photo clicked from the camera or there was an old image that we choose and upload from the application.

Before uploading we can do two things with the image:

1. Change the width and height of original image.
2. Compress the image to be of smaller file size.

Let us understand them.

1. Change the width and height of original image.

To resize the image, we have to configure the drawing environment for rendering into a bitmap.

1# UIGraphicsBeginImageContextWithOptions()  method is used to create the bitmap-based graphics context.

This method takes two parameters:

  1. Size of image (changed size) and
  2. Scale factor of device as parameter.

Scale factor for Normal Display = 1.0
Scale factor for Retina Display = 2.0

2# – (void) drawInRect:(CGRect)rect; method is used to draw the image in target rectangle.

3# UIGraphicsGetImageFromCurrentImageContext()  method is used to get the resized image from drawing environment.

4# UIGraphicsEndImageContext() method is used to clean up the bitmap drawing environment and remove the graphics context from the top of the context stack.

Example :

Original source Image  Size = (2448, 3264)
Original source image file size = 3.8 MB

After resizing image to size (1024,768):
Resized source Image  Size = (1024,768)
Resized source image file size = 2.0 MB

Code Example:

2. Compress the image to be of smaller file size.

We can compress the image file size by following method.

UIImageJPEGRepresentation() This method takes two parameter

  1. UIImage object.
  2. Compress ratio (It can be between 0.0 and 1.0)

This method will return NSData representation of image after compressing.

Example :

Original source Image  Size = (2448, 3264)
Original source image file size = 3.8 MB

After compressing image file  size by 0.5:
Resized source Image  Size = (2448, 3264)
Resized source image file size = 534 KB

Code Example:

Depending upon your requirement whether to reduce the size (width and height in pixels) OR reduce the file size OR Both, you may apply the above.

Original Source: Click Here

iDev: Learn Swift Tutorial Series

Hi Friends,

Hope you all doing good!!!

Now I am start posting to Learning the Swift Language (Apple introduce WWDC 2014). In every tutorial I put example to learn better and best practice way to do the coding.

My first post on Swift will be coming soon on August, In which I explain the basic of Swift and some sample code to understand the structure of Swift language.

Here a snaps of swift :

Arrays

var colors = [“red”, “blue”]
var moreColors: String[] = [“orange”, “purple”] // explicit type
colors.append(“green”) // [red, blue, green]
colors += “yellow” // [red, blue, green, yellow]
colors += moreColors // [red, blue, green, yellow, orange, purple]

var days = [“mon”, “thu”]
var firstDay = days[0] // mon
days.insert(“tue”, atIndex: 1) // [mon, tue, thu]
days[2] = “wed” // [mon, tue, wed]
days.removeAtIndex(0) // [tue, wed]

Classes

class Counter {
var count: Int = 0
func inc() {
count++
}
func add(n: Int) {
count += n
}
func printCount() {
println(“Count: \(count)”)
}
}

var myCount = Counter()
myCount.inc()
myCount.add(2)
myCount.printCount() // Count: 3

Conditionals

//IF STATEMENT
let happy = true
if happy {
println(“We’re Happy!”)
} else {
println(“We’re Sad :(‘”)
}
// We’re Happy!

let speed = 28
if speed <= 0 {
println(“Stationary”)
} else if speed <= 30 {
println(“Safe speed”)
} else {
println(“Too fast!”)
}
// Safe speed

//SWITCH STATEMENT
let n = 2
switch n {
case 1:
println(“It’s 1!”)
case 2…4:
println(“It’s between 2 and 4!”)
case 5, 6:
println(“It’s 5 or 6”)
default:
println(“Its another number!”)
}
// It’s between 2 and 4!

Constants

let myInt = 1
myInt = 2 // compile-time error!

Dictionaries

var days = [“mon”: “monday”, “tue”: “tuseday”]
days[“tue”] = “tuesday” // change the value for key “tue”
days[“wed”] = “wednesday” // add a new key/value pair

var moreDays: Dictionary = [“thu”: “thursday”, “fri”: “friday”]
moreDays[“thu”] = nil // remove thu from the dictionary
moreDays.removeValueForKey(“fri”) // remove fri from the dictionary

Enums

enum CollisionType: Int {
case Player = 1
case Enemy = 2
}
var type = CollisionType.Player

For Loops

for var index = 1; index < 3; ++index {
// loops with index taking values 1,2
}
for index in 1..3 {
// loops with index taking values 1,2
}
for index in 1…3 {
// loops with index taking values 1,2,3
}

let colors = [“red”, “blue”, “yellow”]
for color in colors {
println(“Color: \(color)”)
}
// Color: red
// Color: blue
// Color: yellow

let days = [“mon”: “monday”, “tue”: “tuesday”]
for (shortDay, longDay) in days {
println(“\(shortDay) is short for \(longDay)”)
}
// mon is short for monday
// tue is short for tuesday

Functions

func iAdd(a: Int, b: Int) -> Int {
return a + b
}
iAdd(2, 3) // returns 5

func eitherSide(n: Int) -> (nMinusOne: Int, nPlusOne: Int) {
return (n-1, n+1)
}
eitherSide(5) // returns the tuple (4,6)

Logical Operators

var happy = true
var sad = !happy // logical NOT, sad = false
var everyoneHappy = happy && sad // logical AND, everyoneHappy = false
var someoneHappy = happy || sad // logical OR, someoneHappy = true

Printing

let name = “swift”
println(“Hello”)
println(“My name is \(name)”)
print(“See you “)
print(“later”)
/*
Hello
My name is swift
See you later
*/

Strings

var myString = “a”
let myImmutableString = “c”
myString += “b” // ab
myString = myString + myImmutableString // abc
myImmutableString += “d” // compile-time error!

let count = 7
let message = “There are \(count) days in a week”

Variables

var myInt = 1
var myExplicitInt: Int = 1 // explicit type
var x = 1, y = 2, z = 3 // declare multiple integers
myExplicitInt = 2 // set to another integer value

Source Ref: Press Here

Thanks Friends:)

Keep Coding:)

——————
Mishra Vinay
Solution’s Point

iDev: Copy a plist file to documents folder

Hi Friends,

Here a code snapshot for your help on Copy a plist file to Documents Folder

BOOL isSuccess;
NSError *error;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"idevCopyData.plist"];
isSuccess = [fileManager fileExistsAtPath:filePath];
if (isSuccess) return;
NSString *path = [[[NSBundle mainBundle] resourcePath] stringByAppendingFormat:@"idevCopyData.plist"];
isSuccess = [fileManager copyItemAtPath:path toPath:filePath error:&error];
if (!isSuccess) {
NSAssert1(0, @"Failed to copy Plist. Error %@", [error localizedDescription]);
}

 

Reference : Here

Thanks 🙂

 

iDev: Objective-C Associated Objects

Objective-C Associated Objects

Add properties to objects in categories.

As a developer, I love coming across new methods or techniques that help make better, more readable code. Recently I was trying to find a better way of passing information from a method that creates a UIAlertView to the UIAlertView’s delegate method alertView:didDismissWithButtonIndex:. There is no userInfo dictionary for an alert view, and Apple specifically says not to subclass UIAlertView. What I’ve done in the past is create a property or class instance variable to temporarily hold the object I want to pass around. I don’t like this technique, it feels sloppy, but it gets the job done. Now behold the power of Objective-C Associated Objects.

Associated Objects

Associated objects have been around since iOS 3.1 and are a part of the Objective-C runtime. They allow you to associate objects at runtime. Basically, you can attach any object to any other object without subclassing. To begin using associated objects, all you need to do is import <objc/runtime.h> in the class where you want to use them. The relevant methods are the following:

void objc_setAssociatedObject(id object, void *key, id value, objc_AssociationPolicy policy)
id objc_getAssociatedObject(id object, void *key)
void objc_removeAssociatedObjects(id object)

object is the source object for the association, or in other words, it is the object that will point to the other object.
*key is the the key for the association, this can be any void pointer, anything that has a constant memory address is all you want.
value is the object you want to store or associate with the source object.
policy is a constant defining the type of reference, similar to the types you use when declaring properties. The possible values are:

enum {
   OBJC_ASSOCIATION_ASSIGN = 0,
   OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1,
   OBJC_ASSOCIATION_COPY_NONATOMIC = 3,
   OBJC_ASSOCIATION_RETAIN = 01401,
   OBJC_ASSOCIATION_COPY = 01403
};

 

Typically we don’t want to use objc_removeAssociatedObjects, but would rather use setAssociatedObject with a nil value to remove an association. According to Apple,
The main purpose of this function is to make it easy to return an object to a “pristine state”. You should not use this function for general removal of associations from objects, since it also removes associations that other clients may have added to the object. Typically you should use objc_setAssociatedObject with a nil value to clear an association.

In many cases you probably won’t have to worry about removing an association because when the source object is destroyed it will destroy the reference to the associated object.

Sample Use Case

In my case, I want to associate an NSIndexPath to a UIAlertView. Let me explain my use case a little further, you have probably come across a similar problem. I have a table view where I show a confirmation alert when the user tries to delete a row. Usually I wouldn’t put a confirmation on a delete, but sometimes it has serious implications (maybe you’re deleting a folder holding 100 records of something and deleting the folder deletes all those precious records).

The alert is created and displayed in the UITableViewDataSource method tableView:commitEditingStyle:forRowAtIndexPath:. At this point you have the indexPath you want to delete. Once you call -show on the alert, your class starts waiting for the UIAlertViewDelegate callback methodalertView:didDismissWithButtonIndex:. Once the user confirms, it enters the delegate method and you no longer know which indexPath you should delete.

Now I’m going to detail a number of solutions to this problem, each better than the last. I’m only going to show the relevant code though instead of the entire class because I’m using a very simple example. I just slightly modified the code that is generated for you when you create a new project with the master-detail template (without core data).

Original Solution

The original solution was to have a class level instance variable that holds the index path we want to delete. We would set the index path to delete in our commitEditingStyle method, and then retrieve it in alertView:didDismissWithButtonIndex.

 

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;
    NSIndexPath *_indexPathToDelete;
}

...

- (void)tableView:(UITableView *)tableView commitEditingStyle:
(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
    	NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        _indexPathToDelete = indexPath;
        [deleteConfirmation show];
    }
}

...

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [_objects removeObjectAtIndex:_indexPathToDelete.row];
        [_tableView deleteRowsAtIndexPaths:@[_indexPathToDelete] withRowAnimation:UITableViewRowAnimationFade];
    }
}

 

This solution works, but why would we want to use this instance variable that is visible to the entire class? Only two methods have interest in this index path, and what if some other method messes with indexPathToDelete and we get some unexpected behavior. It would be better if we could confine this object to only the methods that care about it.

Acceptable Solution

Using the objective-c runtime methods we can associate the index path to the alert view. We will set the association in commitEditingStyle, and retrieve the index path in didDismissWithButtonIndex:.

 

#import <objc/runtime.h>

static char deleteKey;

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;
}

...

- (void)tableView:(UITableView *)tableView 
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        objc_setAssociatedObject(deleteConfirmation, &deleteKey, indexPath, OBJC_ASSOCIATION_RETAIN);
        [deleteConfirmation show];
    }
}

...

- (void)alertView:(UIAlertView *)alertView 
didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSIndexPath *deletePath = objc_getAssociatedObject(alertView, &deleteKey);
        [_objects removeObjectAtIndex:deletePath.row];
        [_tableView deleteRowsAtIndexPaths:@[deletePath] 
                               withRowAnimation:UITableViewRowAnimationFade];
    }
}

 

As you can see, we no longer need the instance variable, but we use a new static char variable as the association key. The alert view holds a strong reference to the index path, so it persists from one method to the next as long as the alert view is still in memory. When the alert view is destroyed it will also destroy the index path associated with it. This makes the code clearer and confined to just the methods it is used in instead of having an instance variable that is available to the whole class. We can make this code even better though.

Better Solution

Associated Objects Category

You can create a category on NSObject that simplifies the objective-c runtime calls into a nice API you can use in your normal classes. You could expand on this, but a basic category would be as follows:

NSObject+AssociatedObjects.h

@interface NSObject (AssociatedObjects)
- (void)associateValue:(id)value withKey:(void *)key;
- (id)associatedValueForKey:(void *)key;
@end

 

NSObject+AssociatedObjects.m

#import "NSObject+AssociatedObjects.h"
#import <objc/runtime.h>

@implementation NSObject (AssociatedObjects)

- (void)associateValue:(id)value withKey:(void *)key
{
    objc_setAssociatedObject(self, key, value, OBJC_ASSOCIATION_RETAIN);
}

- (id)associatedValueForKey:(void *)key
{
    return objc_getAssociatedObject(self, key);
}

@end

 

Your view controller would then look like this…

 

#import "NSObject+AssociatedObjects.h"
static char deleteKey;

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;
}

...

- (void)tableView:(UITableView *)tableView 
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        [deleteConfirmation associateValue:indexPath withKey:&deleteKey];
        [deleteConfirmation show];
    }
}

...

- (void)alertView:(UIAlertView *)alertView 
didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSIndexPath *deletePath = [alertView associatedValueForKey:&deleteKey];
        [_objects removeObjectAtIndex:deletePath.row];
        [_tableView deleteRowsAtIndexPaths:@[deletePath] 
                    withRowAnimation:UITableViewRowAnimationFade];
    }
}

 

I like this a little better because it abstracts out the runtime methods and gives you a nice interface you can use on any object. This accomplishes the same thing, but to me it is much more readable and feels better.

Awesome Solution

According to Apple docs:
The UIAlertView class is intended to be used as-is and does not support subclassing. The view hierarchy for this class is private and must not be modified.

Also according to Apple docs:
Categories can be used to declare either instance methods or class methods but are not usually suitable for declaring additional properties. It’s valid syntax to include a property declaration in a category interface, but it’s not possible to declare an additional instance variable in a category. This means the compiler won’t synthesize any instance variable, nor will it synthesize any property accessor methods. You can write your own accessor methods in the category implementation, but you won’t be able to keep track of a value for that property unless it’s already stored by the original class.

The only way to add a traditional property-backed by a new instance variable-to an existing class is to use a class extension, as described in ‘Class Extensions Extend the Internal Implementation.'”

With our newfound power, we will add a new property to UIAlertView without subclassing it. As you see in the documentation, it is perfectly valid to declare a property in the category interface, you just can’t create a new instance variable. We don’t need a new instance variable, we will just override the getter and setter of our property to store and retrieve the property by associating it to the alert view.

Let’s create a category on UIAlertView called DeleteConfirmation.

In UIAlertView+DeleteConfirmation.h

@interface UIAlertView (DeleteConfirmation)
@property (nonatomic) NSIndexPath *indexPathToDelete;
@end

 

Now in UIAlertView+DeleteConfirmation.m

#import "UIAlertView+DeleteConfirmation.h"
#import "NSObject+AssociatedObjects.h"

@implementation UIAlertView (DeleteConfirmation)

- (void)setIndexPathToDelete:(NSIndexPath *)indexPathToDelete
{
    [self associateValue:indexPathToDelete withKey:@selector(indexPathToDelete)];
}

- (NSIndexPath *)indexPathToDelete
{
    return [self associatedValueForKey:@selector(indexPathToDelete)];
}

@end

 

Thanks to Erica Sadun, who then credits Gwynne Raskind, for this bad-assery of using the property selector as the association key. According to them, this is valid because Apple’s selector implementation uses a fixed address.

Using the same example, after importing the new category, our view controller code becomes:

 

#import "UIAlertView+DeleteConfirmation.h"

@interface MasterViewController () <UIAlertViewDelegate> {
    NSMutableArray *_objects;
}

...

- (void)tableView:(UITableView *)tableView
 commitEditingStyle:(UITableViewCellEditingStyle)editingStyle 
forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSString *deleteMessage = @"Are you sure you want to delete this super important thing?";
        UIAlertView *deleteConfirmation = [[UIAlertView alloc] initWithTitle:@"Delete Row"
                                                                     message:deleteMessage
                                                                    delegate:self
                                                           cancelButtonTitle:@"Cancel"
                                                           otherButtonTitles:@"Confirm", nil];
        deleteConfirmation.indexPathToDelete = indexPath;
        [deleteConfirmation show];
    }
}

...

- (void)alertView:(UIAlertView *)alertView 
didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        NSIndexPath *deletePath = alertView.indexPathToDelete;
        [_objects removeObjectAtIndex:deletePath.row];
        [_tableView deleteRowsAtIndexPaths:@[deletePath] 
                            withRowAnimation:UITableViewRowAnimationFade];
    }
}

 

Beautiful. I love it. The index path to delete looks like any other property you would access.

Conclusion

Ok… maybe this is overkill for the example I gave, but I’m sure you will find other uses for it now that you know about it. It is a great weapon to have at your disposal, and it really helps you write much cleaner, self documenting code.

Source Reference : Press Here

iDev: How to extend existing method in Objective-C

Hi Friends,

Todays you learn a very good technique, I hope:)

With blocks it’s more easy if you need extend your method. But if you will need extend some method of another class, not yours, and you will not be able to get the sources then this solution for you. (And if you will not be able or does not have any reason for creating a subclass)

1. You need create a category of class

2. import runtime in implementation file (.m)

#import <objc/runtime.h>

3. implement your method inside category, for example :

– (void) extend_method {

// your code

//  here will be performed the original method
[self extend_method];

// your code
}

It looks like this method has recursive calls itself, but it’s not true. Look next step

4. add method for replace (you can use +initialize or +load)

+ (void) initialize {
Method original = class_getInstanceMethod(self, @selector(method));
Method replacement = class_getInstanceMethod(self, @selector(extend_method));
method_exchangeImplementations(original, replacement);
}

Done!

Reference : Press Here

Keep Coding 🙂

 

iDev: Secure site trust (Https:) in iOS using NSURLConnection

Secure Coding iPhone and iPad Apps Against MiTM

Many iOS applications use HTTP to connect to server side resources. To protect user-data from being eavesdropped, iOS applications often use SSL to encrypt their HTTP connections.

In this article, I will present sample Objective-C code to illustrate how HTTP(S) connections are established and how to locate insecure code that can leave the iOS application vulnerable to Man in the Middle attacks. I will also discuss how to configure an iOS device to allow for interception of traffic through an HTTP proxy for testing purposes.

A Simple App Using NSURLConnection

The easiest way to initiate HTTP requests in iOS is to utilize the NSURLConnection class. Here is sample code from a very simple application that takes in a URL from an edit-box, makes a GET request, and displays the HTML obtained.

[Please note that the code in this particular example is mostly from Apple’s wonderful tutorial on how to use NSURLConnection]

//This IBAction fires when the user types in a URL and presses GO
– (IBAction) urlBarReturn:(id)sender
{   
    //htmlOutput is the UITextView that displays the HTML
    htmlOutput.text=@””;

    //urlBar is the UITextField that contains the URL to load
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlBar.text]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                              timeoutInterval:60.0];
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

    if(!theConnection)
        htmlOutput.text=@”failed”;   
}

– (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

{
    //receivedData is of type NSMutableData
    [receivedData setLength:0];

}

– (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [receivedData appendData:data];

    NSString *tempString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    htmlOutput.text = [NSString stringWithFormat:@”%@%@”,htmlOutput.text,tempString];

    [tempString release];
}

– (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

    [connection release];

    [receivedData release];

    NSLog(@”Connection failed! Error: %@ %@”,
          [error localizedDescription],
          [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);

    htmlOutput.text=[NSString stringWithFormat:@”Connection failed! Error %@ %@”,[error localizedDescription],
                     [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
}

– (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@”Succeeded! Received %d bytes of data”,[receivedData length]);

    [connection release];

    [receivedData release];

}

The result is a simple iOS application that fetches HTML code from a given URL.

IOS-app-simple-html
Figure: Simple iOS App using NSURLConnection to fetch HTML from a given URL.

In the screen-shot above, notice that the target URL is https. NSURLConnection seamlessly establishes an SSL connection and fetches the data. If you are reviewing source code of an iOS application for your organization to locate security issues, it makes sense to analyze code that uses NSURLConnection. Make sure you understand how the connections are being inititated, how user input is utilized to construct the connection requests, and if SSL is being used or not. While you are at it, you may also want to watch for NSURL* in general to include invocations to objects of type NSHTTPCookie, NSHTTPCookieStorage, NSHTTPURLResponse, NSURLCredential, NSURLDownload, etc.

Man in the Middle 

74.125.224.49 is one of the IP addresses bound to the host name http://www.google.com. If you browse to https://74.125.224.49, your browser should show you a warning due to the fact that the Common Name field in the SSL certificate presented by the server (www.google.com) does not match the host+domain component of the URL.

IOS-safari-warning Figure: Safari on iOS warning the user due to mis-match of the Common Name field in the certificate.

As presented in the screen-shot above, Safari on iOS does the right thing by warning the user in this situation. Common Name mis-matches and certificates that are not signed by a recognized certificate authority can be signs of a Man in the Middle attempt by a malicious party that is on the same network segment as that of the user or within the network route to the destination.

Ios-NSURL-warning Figure: NSURLConnection’s connection:didFailWithError: delegate is invoked to throw a similar warning.

The screenshot above shows what happens if we attempt to browse to https://74.125.224.49 using our sample App discussed ealier: the connection:didFailWithError: delegate is called indicating an error, which in this case warns the user of the risk and terminates.

This is fantastic. Kudos to Apple for thinking through the security implications and presenting a useful warning message to the user (via NSError).

Unfortunately, it is quite common for application developers to over-ride this protection for various reasons: for example, if the test environment does not have a valid certificate and the code makes it to production. The code below is enough to over-ride this protection outright:

 

– (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace

{
    return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}

– (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge

{
                [challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
}

The details on this code is available from this stackoverflow post. There is also a private method for NSURLRequest called setAllowsAnyHTTPSCertificate:forHost: that can be used to over-ride the SSL warnings but Apps that use it are unlikely to get through the App store approval process (Apple prohibits invocations of private API).

If you are responsible for reviewing your organization’s iOS code for security vulnerabilities, I highly recommend you watch for such dangerous design decisions that can put your client’s data and your company’s data at risk.

Intercepting HTTPS traffic using an HTTP Proxy.

As part of performing security testing of applications, it is often useful to intercept HTTP traffic being invoked by the application. Applications that use NSURLConnection‘s implementation as-is will reject your local proxy’s self-signed certificate and terminate the connection. You can get around this easily by implanting the HTTP proxy’s self-signed certificate as a trusted certificate on your iOS device [Note: This is not a loop-hole against the precautions mentioned above: in this case we have access to the physical device and are legitimately implatining the self-signed certificate].

If you are using the Burp Proxy or the Charles Proxy, all you need to do is place the self-signed cert on a HTTP location and browse to it. Instructions for the Burp Proxy are available here, and instructions for Charles Proxy are also available.

Once you have your iOS device or simulator setup using the self-signed certificate of your HTTP proxy, you should be able to intercept HTTPS connections that would otherwise terminate. This is useful for fuzzing, analyzing, and testing iOS applications for security issues.

Source Reference : Click Here..

Thanks 🙂

Keep Coding and innovation new thing in your code … 😉

 

iDev : Essential Tools for iOS Developers

75 Essential Tools for iOS Developers

Source Reference : Here

If you were to go to a master woodworker’s shop, you’d invariably find a plethora of tools that he or she uses to accomplish various tasks.

In software it is the same. You can measure a software developer by how they use their tools. Experienced software developers master their tools. It is important to learn your current tools deeply, and be aware of alternatives to fill in gaps where your current ones fall short.

With that in mind, I present to you a gigantic list of tools. Some of these I use daily, others I see potential in. If you have more tools you’d like to see here, just make sure to add a comment.

I tried to categorize these the best I can. Some of the entries are websites, some are back-end services, but most are apps that you install. Not all of the apps are free, so I’ll make a note with a $ to denote that an app costs money.

And without further ado, we’ll start from the beginning of any project, and that

Inspiration

  • pttrns – A great library of iOS screen designs categories by task. If you want to see how other apps handle activity feeds, for instance, this is a great place to go see a bunch of examples.
  • TappGala – Another great collection of nice app designs. It’s not categorized by task, but is just a list of great apps to get inspiration from.
  • Cocoa Controls – A great list of components (code) that you can use in your iOS apps. Sometimes you’ll find great pieces of code that can save you time, other times you can just learn how other developers accomplish certain features. Subscribe to their weekly newsletter; all signal, little noise.
  • IICNS – A collection of really great icons. Get inspired, but don’t copy.
  • Dribbble – Some of the best digital designers post up their work for all to see. A treasure-trove of designs to look at.
  • Capptivate – a gallery of inspirational designs. Some contain animations. Thanks, @joaopmaia!

Design

  • Mocks ($) – An easy to use tool to create a quick mockup of an iOS app. Comes with a bunch of the default controls you can use to assemble something quickly.
  • Briefs ($) – A really useful app that allows you to create a mockup of an app and stitch them together so you can see the interaction. Deploy to a device so you can see what it feels like in your hand.
  • Acorn ($) – A strong competitor to Photoshop, only way cheaper. I find myself reaching for Photoshop less & less these days. Under active development.
  • Sketch ($) – A vector-based drawing tool that is increasingly useful these days, as screen sizes and pixel densities change. It is often helpful to design once and have the freedom to scale up & down as needed. Also sports a really powerful export system. For some example Sketch projects, check out Sketchmine. See my screencast on Sketch for a live demo.
  • iOS 7 PSD by Teehan+Lax – A super handy resource if you (or your designer) uses Photoshop. An iOS 6 version is also available.
  • Bjango’s Photoshop Actions – A definite time-saver if you use Photoshop to design iOS apps. One click access to resize canvases, scale by 200% (or 50%), set global lighting to 90º, and more. Their blog also has a bunch of useful Photoshop workflow tips.
  • xScope ($) – An indespensible swiss-army knife of tools such as guides, pixel loupes, screen rulers, and more. Want to know what color value that pixel is? Want to see how many pixels between a button and the window for a random Mac app? xScope has you covered. Also check out their companion iPhone app for mirroring designs you’re working on and seeing them in pixel-perfect glory on your iDevice.
  • Glyphish ($) – A fantastic collection of high quality icons for your iOS apps. Apple doesn’t provide a lot of built-in icons, so it’s handy to have a collection of icons covering all kinds of various concepts. I’m still looking for a use for that baby icon though. Glyphish comes in packs, and the latest pack has iOS 7 “thin line” icons which will be very handy when designing an iOS 7 app.
  • Fontastic Icons for iOS – An open source set of classes for utilizing icon fonts, such as Font Awesome in your iOS app. Quickly and easily have an icon in whatever pixel dimensions you require. Since fonts by nature can be scaled up and down with ease, this makes a really nice way to ship & use your icons without having to export multiple versions for the sizes you require.
  • PaintCode ($) – A vector-based drawing tool that exports your artwork as the equivalent Core Graphics source code. Awesome for learning how Core Graphics drawing works, but also incredibly handy if you want your drawing to be dynamic. See my screencast on PaintCode for a live demo.
  • Edge Insets ($) – A simple tool that helps you define your edge insets for repeatable images. Available on the Mac App Store.
  • LiveView – A remote screen viewer for iOS, making it easy to immediately see your designs on a device. Thanks, @_funkyboy!
  • Skala Preview ($) – Another excellent tool for quickly showing your designs off on a real device. The guys at Bjango are awesome and this app is deserving of the price. Thanks, jn40!

Source Control

  • Git – If you’re not using source control stop what you’re doing and rectify that. I use git for everything I do and love it.
  • Kaleidoscope ($) – The best diff/merge tool around. Does 3-way merges and is beautiful to look at. I use it every day.
  • p4merge – A free, ugly alternative to Kaleidoscope. Powerful 3-way merge, but good luck finding the download link. It’s hidden deeper in their site every time I look for it.
  • Git X – A simple, powerful GUI tool for visualizing git timelines and quickly & easily staging commits. I usually live in the Terminal for git usage, but fall back to this app when I need to stage hunks of changes into logical commits. This is a fork of the original (abandoned) GitX, which I found on this list of forks.
  • Source Tree – A free, full-featured Git application. I don’t use this because I favor the command line, but if a GUI tool is your cup-o-tea, check this app out.

Dissecting Apps

  • pngcrush – This little utility can crush & uncrush PNG files, which is handy when you want to view images contained in app bundled distributed in the App Store. Just open iTunes, view the local Apps list, and right click on any icon to Show in Finder. Once there, open up the app and you’ll see a bunch of PNG files, but you can’t view them. Using pngcrush you can extract the full version so it can be opened with Preview.
  • appcrush.rb – This handy little ruby script will automate the above process for all images. Just point it to a .app file on your disk and it will extract all the images to a folder on your desktop. Handy for seeing how apps on your phone accomplish certain designs. Check out my screencast on dissecting apps for a live demo.
  • Charles ($, free limited demo) – I don’t know what’s going on with the ugly UI or icon, but Charles is an essential tool for any developer. Charles acts as a proxy to allow you to inspect your network traffic to & from the iPhone Simulator. You can also inspect traffic from your device by setting your phone’s proxy to your Mac running Charles. With self-signed SSL certificates, request & response breakpoints, and request/response viewers, Charles is really amazingly powerful. A must-have tool. Again, my screencast on dissecting apps covers this well.

Editors

I know what you’re thinking, don’t all iOS developers use Xcode? Well mostly, yes. But with my love/hate relationship with Xcode, I believe there is tremendous value in considering alternatives.

  • AppCode – A full-fledged IDE from Jetbrains (makers of the excellent ReSharper for .NET). Immensely powerful refactorings & features that help you write code faster. Quickly identify dead code, automatically insert #import statements when you use related code, easily extract variables, methods, and classes. My only wish for this app is that it would instead be a plugin to Xcode.
  • Vim – Wait, vim? Really? Yes, there are folks who do all their Objective-C development in vim. I’m not one of these, but I am a fan of vim for Ruby development. As such, I’m a huge fan of…
  • Xvim – An Xcode plug-in that gives you vim keybindings. Works well, ‘nuff said.
  • OMColorSense – Another plugin for Xcode, this one gives you a small display of color when your cursor is on a line looking like: [UIColor redColor]. Clicking on this little color tab opens a color picker that you can change, and any change in color you make is reflected in the code by changing the line to [UIColor colorWithRed:… green:… blue:… alpha:… ]. When someone is watching me write code with this enabled, they invariably ask me, “Whoa! What was that?!”
  • KSImageNamed – Another Xcode plug-in, this one allows you to autocompleted image filenames from your bundle when typing [UIImage imageNamed:…]. Great way to avoid the inevitable typo that causes this method to return nil and you to subsequently waste 10 minutes trying to figure out why your images aren’t displaying.
  • CocoaPods Xcode Plugin – This plug-in adds a menu item for interacting with CocoaPods. Useful if you don’t like dropping to the command line.
  • Alcatraz Package Manager – An awesome meta plug-in that allows you to easily install other Xcode color schemes and plug-ins with a single click.
  • Code Runner ($) – a light-weight code-aware text editor that knows how to compile & run code in most languages. Want to test out a quick snippet of Objective-C code and don’t want to create an entire Xcode project to do it? Code Runner to the rescue.

Documentation

Ahhh, documentation, everyone’s favorite topic. Even still, documentation is really important to have, so pay attention so we can make your life easier.

  • appledoc – Want to automatically generate documentation that look’s like Apple’s? Look no further. Automatically inter-links symbols defined in your project as well as extracting discussion to output using specially formatted code-comments. Generates official docsets and HTML web sites.
  • Dash ($) – A must-have API documentation viewer and code snippet manager. This tool is really handy as it allows you to download & search API docs for all kinds of languages & frameworks with lightning speed. The fastest way to get access to the docs. I integrate Dash with Alfred to make searches even faster.

Dependency Management

Yes, there’s only one tool listed here. I didn’t want to include actual 3rd party libraries, as that would be a different list entirely. When it comes to dependency management, there’s only one game in town:

  • CocoaPods – The essential tool for Objective-C projects. Allows you to quickly & easily integrate 3rd party libraries into your application. It does so by creating a second static library project and automatically links this with your projects. There are thousands of pods available, and it’s easy to add support for libraries that you don’t own (or perhaps are private). I use CocoaPods in every single project I work on.

Diagnostics & Debugging

At some point our app is in the field and we need to understand better what’s going on, maybe to fix bugs or to improve performance.

  • Cocoa Lumberjack – a much more powerful NSLog, Cocoa Lumberjack offers advanced logging behaviors such as logging to rotated files, logging to the network, and filtering based on log level (info, debug, warn, error). Covered by NSScreencast Episode 61
  • DCIntrospect – crazy powerful tool that you’d link inside your app when running in debug and on the simulator. Once you do, you can press the spacebar to get some really helpful view debugging support. See exact dimensions of elements on the screen, print out view hierarchies, even nudge views horizontally or vertically.
  • Pony Debugger – another tool you’d use by embedding a library in your debug builds, Pony Debugger actually utilizes Chrome’s dev tools for seeing network requests coming out of the device, as well as a rudimentary Core Data browser. It’s hard to describe, but check out my screencast on Pony Debugger for more info.
  • Runscope ($) – Runscope is a service running online that can capture requests, log details, and give you valuable data about your API. Simple to set up, as it’s an HTTP pass-through API, all you need to change is your host name.
  • SimPholders – Quick, easy access to your simulator folders. Browse by iOS version, then app name and jump right to the folder in Finder.
  • Spark Inspector ($) – Debug your view hierarchy running on your app in debug mode, in 3D. This app really has to be seen to fully understand the value, but it can really help to understand what views are used to compose your app. Also contains a notification center inspector, so you can easily see what NSNotifications are firing and who is observing them. Another app to look at that is similar is Reveal.

Images

  • ImageAlpha – A Mac app that allows you to convert a 24-bit PNG with transparency to an 8-bit PNG with an alpha channel. Typically 8-bit PNGs don’t have an alpha channel, so if your image can be represented in 8-bits (say, a solid color button) you can save a lot on storage by converting the 24-bit PNG to 8-bit using ImageAlpha.
  • ImageOptim – Another Mac app that compresses PNGs in order to save space. Most PNG files can shave off a few % of the size, and sometimes you’ll shrink the files by 30% or more. Smaller images mean smaller app sizes and less memory used to load them at runtime.
  • Prepo – A little Mac app that can quickly resize artwork in all the various sizes you might need. Just drag a large icon file (say, 1024×1024) onto Prepo and watch it spit out 512×512 iTunesArtwork, 114×114 Icon@2x.png, and all the other sizes & filenames you’d expect.
  • Slender ($) – an awesome app that analyzes your app and finds all sorts of problems, such as missing retina artwork, unused images, image that could benefit from compression and more. Shave kilobytes off of your iPhone app by shedding unused images with Slender.

Core Data

  • Mogenerator – still a super useful tool for generating smart subclasses of your NSManagedObjects in your Core Data model. Some use Xcode for this, and resort to manually subclassing or creating categories in order to add logic to the models. Mogenerator runs as a quick pre-compile script to generate subclasses for you to use. It does this by creating an underscored version (_User) and a regular one for you to modify (User).
  • Base ($) – there will come a time when you need to inspect your actual Core Data sqlite database to see what’s going on. You can use the sqlite3 command line tool, but Base offers a nice looking GUI browser. Just don’t vomit when you see the database schema that Core Data created for you.
  • Core Data Editor ($) – for more advanced data anlysis, exploration, and modification you can use Core Data Editor. This app understands Core Data, so you’re working directly with the entities instead of database rows.

Back-end Services

Ultimately your iOS app will likely want to talk to a server to share data, fetch new content, send push notifications or whatever. While this can be accomplished manually, you might want a more drop-in solution.

  • Helios – Helios is an open-source framework that provides essential backend services for iOS apps, from data synchronization and push notifications to in-app purchases and passbook integration. Built on top of many open source ruby gems, so you can pick & choose and build your own stack if you so desire. Take a look at the Nomad CLI set of handy related tools as well.
  • Windows Azure Mobile Services – you can think of this sort of like a programmable database in the cloud. Create tables, run JavaScript on read, insert, delete to add additional functionality. Really easy support for push notifications as well.
  • Urban Airship – I’ve been using Urban Airship to deliver push notifications for a while now. Really easy to integrate with, and small usage is free.
  • Parse – This is another data-in-the-cloud service, but offers an impressive API and online data browser. We use Parse for a really small app and works well for that.

Analytics

There are other players here, but none that I’ve seen have been compelling enough to switch from flurry. I’m open to hearing suggestions, so let’s hear about ‘em in the comments.

  • Flurry – I’ve used flurry for a long time to provide useful analytics on the usage of my apps. Need to know when to stop supporting iOS 5? Flurry gives you the numbers to have a realistic conversation.

Deployment

  • Deploymate ($) – Need to support iOS 4 still, but you’re compiling with the iOS 6 SDK? Deploymate will warn you when you’re using symbols that don’t exist in your deployment target.
  • Cupertino – Part of the Nomad CLI tools, Cupertino gives you command line access to managing devices & profiles in the Apple Provisioning Portal. For example, just type ios devices:list to see the current list of devices in your account. Useful for automating lots of processes.
  • Hockey App ($) – A great service for managing the distribution of your ad-hoc builds. Testers can get a link to install new betas over the air. Also provides robust crash reporting so you can easily respond to crashes in your apps.
  • TestFlight – A free service, similar to Hockey App. We’ve used TestFlight with great success for easily distributing apps and collecting feedback from our users. My only wish is that they’d start charging for the service. Also includes analytics and crash reporting, but we don’t use those features.
  • iOS Simulator Cropper – A really easy way to snap images of the simulator, with or without status bar, with or without device chrome, etc. Great for taking App Store or just general marketing screenshots.
  • Status Magic ($) – Take better app store screenshots. Nothing makes your app look less crappy than an App Store screenshot that includes a low battery, or low signal. Status Magic gives you complete customization over what’s present in your status bar, including removing elements, changing the time to “9:41 AM” like Apple tends to do, and more.
  • Crashlytics – Excellent crash reporting for your apps in the field. Automatically uploads dSYMs on release builds so your crashes are automatically symbolicated and organized for you to focus on the most critical ones.

Testing

I don’t think we as a community focus enough on testing. There are great tools available to us, and most are so easy to use we have no real excuse not to write at least some tests for our apps.

  • Kiwi – A great Rspec-style testing framework for iOS. Built on top of SenTestingKit, so you just type ⌘U to run your specs. Also includes a completely robust mocking & stubbing library as well as assertions.
  • Specta – A light-weight BDD framework very similar to Kiwi, but the expectation syntax has one major benefit over Kiwi: everything is implicitly boxed like this: expect(items.count).to.equal(5). There’s no need to wrap 5 in an NSNumber like Kiwi does. Use in conjunction with Expecta for a bunch of useful matchers.

The following are all various ways of performing end-to-end acceptance tests. These tests will actually interact with your interface, touching buttons, scrolling, etc. By nature these will be slower and more brittle, but testing in broad strokes is certainly helpful to see if all of the pieces fit together properly.

Demos / Marketing

  • Reflector ($) – Wirelessly mirror your iOS device on your Mac using Air Play. Great for doing demos of applications on your computer.
  • Placeit – A great collection of high res photos of people using devices, but the screens are templates that you can insert your own screenshots into. Very cool, and great for displaying your app in a nice way on your website.

App Sales Reporting

Of course you want to be able to see how much money you’re making on your app, right? There are a few solutions for this, but here are a couple that work well:

  • App Viz 2 ($) – a really useful Mac app for tracking sales of your apps. You run it locally and it logs in and downloads your sales reports.
  • App Annie – an online sales reporting tool. I’m less comfortable giving my credentials to iTunes to a 3rd party, but it does keep the reports up to date for you so you don’t have to run an app locally. In the comments, Josh Brown suggests creating a different user for analytics in iTunes Connect, which is a really good idea.

Grab Bag

These tools don’t have a defined category above, but deserve a mention nonetheless.

  • Quick Radar – Submitting bug reports to Apple is our only way of making their tools better. If you’re frustrated by the lack of a feature, you should be submitting a bug report. If you come across a bug, you should be submitting a bug report. One has no right to complain if they have not yet filed a radar :). With that in mind, submitting bug reports via bugreporter feels like a trip back to 1995. Quick Radar is an awesome little app that makes submitting bug reports super easy. Sports automatic posting to open radar so others can see it, in addition to tweeting, and posting to App.net. I use this app several times per week.

Thanks 🙂

Keep Reading and Experiment on your code….

 

iDev: iOS Device not detect by xcode-5

Hi Friends,

Today I found a one major issue with XCode, Actually I upgarde my iOS Devices (6.0 to 7.1 ) , after that my device not detected by Xcode 5.0,with this error on organizer,

“The version of iOS on “iPhone/iPad ” is not supported by this installation of the iOS SDK. Please restore the device to a version of the OS listed below, or update to the latest version of the iOS SDK; which is available here.”

Solution:

Please upgrade your XCode to 5.1 and above version using the OS X App Store application, your reference links are :

And fix this issue.

For Reference : Here

Thanks 🙂

 

iDev : Create, Rename, Delete, Read and Write File on iOS Functions

Hi Friends,

On iOS Programming, one of the most frequent tasks is Manipulation with Files. Using Local Files is one of the most efficient way to store your local data, other ways may include NSUserDefault, Core Data, but local files is very easy to be implemented and organized. So in this tutorial, we will focus on 5 main manipulation related to Local File on iOS.

Before we get started, we first should know what files have been stored in your app’s sandbox. As you might know, every app on iPhone is like an island, usually we name it SandBox. It contains AppName.app, Library folder, tmp folder and Document folder. User usually have their data stored in Document folder if they choose to use local file to store their data because other folders are not designed to store user’s data. So here we use Document Folder to give our test.

So, let’s list all the files exists in Document Folder in our Sandbox.

 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

– (void)listAllLocalFiles

{

// Fetch directory path of document for local application.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

// NSFileManager is the manager organize all the files on device.

NSFileManager *manager = [NSFileManager defaultManager];

// This function will return all of the files’ Name as an array of NSString.

NSArray *files = [manager contentsOfDirectoryAtPath:documentsDirectory error:nil];

// Log the Path of document directory.

NSLog(@”Directory: %@”, documentsDirectory);

// For each file, log the name of it.

for (NSString *file in files) {

NSLog(@”File at: %@”, file);

}

}

1, Create a File in the Document Folder.

 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

– (void)createFileWithName:(NSString *)fileName

{

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

NSFileManager *manager = [NSFileManager defaultManager];

// 1st, This funcion could allow you to create a file with initial contents.

// 2nd, You could specify the attributes of values for the owner, group, and permissions.

// Here we use nil, which means we use default values for these attibutes.

// 3rd, it will return YES if NSFileManager create it successfully or it exists already.

if ([manager createFileAtPath:filePath contents:nil attributes:nil]) {

NSLog(@”Created the File Successfully.”);

} else {

NSLog(@”Failed to Create the File”);

}

}

2, Delete a File in the Document Folder.

 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

– (void)deleteFileWithName:(NSString *)fileName

{

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

// Have the absolute path of file named fileName by joining the document path with fileName, separated by path separator.

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

NSFileManager *manager = [NSFileManager defaultManager];

// Need to check if the to be deleted file exists.

if ([manager fileExistsAtPath:filePath]) {

NSError *error = nil;

// This function also returnsYES if the item was removed successfully or if path was nil.

// Returns NO if an error occurred.

[manager removeItemAtPath:filePath error:&error];

if (error) {

NSLog(@”There is an Error: %@”, error);

}

} else {

NSLog(@”File %@ doesn’t exists”, fileName);

}

}

3, Rename a File in the Document Folder.

 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

– (void)renameFileWithName:(NSString *)srcName toName:(NSString *)dstName

{

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *filePathSrc = [documentsDirectory stringByAppendingPathComponent:srcName];

NSString *filePathDst = [documentsDirectory stringByAppendingPathComponent:dstName];

NSFileManager *manager = [NSFileManager defaultManager];

if ([manager fileExistsAtPath:filePathSrc]) {

NSError *error = nil;

[manager moveItemAtPath:filePathSrc toPath:filePathDst error:&error];

if (error) {

NSLog(@”There is an Error: %@”, error);

}

} else {

NSLog(@”File %@ doesn’t exists”, srcName);

}

}

4, Read a File in the Document Folder.

 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

/* This function read content from the file named fileName.

*/

– (void)readFileWithName:(NSString *)fileName

{

// Fetch directory path of document for local application.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

// Have the absolute path of file named fileName by joining the document path with fileName, separated by path separator.

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

// NSFileManager is the manager organize all the files on device.

NSFileManager *manager = [NSFileManager defaultManager];

if ([manager fileExistsAtPath:filePath]) {

// Start to Read.

NSError *error = nil;

NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSStringEncodingConversionAllowLossy error:&error];

NSLog(@”File Content: %@”, content);

if (error) {

NSLog(@”There is an Error: %@”, error);

}

} else {

NSLog(@”File %@ doesn’t exists”, fileName);

}

}

5, Write a File in the Document Folder.

 1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

/* This function Write “content” to the file named fileName.

*/

– (void)writeString:(NSString *)content toFile:(NSString *)fileName

{

// Fetch directory path of document for local application.

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

// Have the absolute path of file named fileName by joining the document path with fileName, separated by path separator.

NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];

// NSFileManager is the manager organize all the files on device.

NSFileManager *manager = [NSFileManager defaultManager];

// Check if the file named fileName exists.

if ([manager fileExistsAtPath:filePath]) {

NSError *error = nil;

// Since [writeToFile: atomically: encoding: error:] will overwrite all the existing contents in the file, you could keep the content temperatorily, then append content to it, and assign it back to content.

// To use it, simply uncomment it.

//        NSString *tmp = [[NSString alloc] initWithContentsOfFile:fileName usedEncoding:NSStringEncodingConversionAllowLossy error:nil];

//        if (tmp) {

//            content = [tmp stringByAppendingString:content];

//        }

// Write NSString content to the file.

[content writeToFile:filePath atomically:YES encoding:NSStringEncodingConversionAllowLossy error:&error];

// If error happens, log it.

if (error) {

NSLog(@”There is an Error: %@”, error);

}

} else {

// If the file doesn’t exists, log it.

NSLog(@”File %@ doesn’t exists”, fileName);

}

// This function could also be written without NSFileManager checking on the existence of file,

// since the system will atomatically create it for you if it doesn’t exist.

}

Appending the file and add another text continously used this on Write menthod

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *docPath = [documentsDirectory stringByAppendingPathComponent:@”File.txt”];

NSString *appendString = //Your appending string ;

NSFileHandle *myHandle = [NSFileHandle fileHandleForWritingAtPath:docPath];

[myHandle seekToEndOfFile];

[myHandle writeData:[savedString dataUsingEncoding:NSUTF8StringEncoding]];

Also, similar API applies to URL and Directory. Check Apple’s Doc for more details.

iDev: UISearchBar Tricks – Showing The Cancel And The Scope Bar Only When Editing

UISearchBar Tricks – Showing The Cancel And The Scope Bar Only When Editing

While working on a particular UISearchBar I ran into 2 little problems, both easy to fix but I thought of posting them in case someone is stuck. What I needed was to make the cancel button and the scope bar to be displayed only while editing. I believe that this should be a pretty common thing to do, and the first part is pretty straight forward:

– (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {

searchBar.showsCancelButton = YES;

return YES;

}

– (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {

searchBar.showsCancelButton = NO;

return YES:

}

That is pretty simple, specially if you don’t forget to associate the UISearchBar’s delegate!

Next, I tried the same with the scope bar but it didn’t work – the scope bar wouldn’t appear. During my testing, I tried to start with the scope bar displayed and then hiding it after the first edit… it worked but when disappearing the search bar would preserve the height as if it was still showing the scope bar!

The final solution is a simple call to [searchBar sizeToFit] and everything works as smooth as it should. Here is the complete code with the small bonus of animating the cancel button’s (dis)appearance:

– (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {

searchBar.showsScopeBar = YES;

[searchBar sizeToFit];

[searchBar setShowsCancelButton:YES animated:YES];

return YES;

}

– (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar {

searchBar.showsScopeBar = NO;

[searchBar sizeToFit];

[searchBar setShowsCancelButton:NO animated:YES];

return YES;

}