Category Archives: Objective-C

Making a GridView in iOS using UICollectionView.

Hey all,

In Today’s article you will study about the implementation of UICollectionView in iOS.
It is similar to GridView in Android.

UICollectionView in iOS

First drag a UICollectionView [Not the Collection View Controller] in your interface and let it be there.
we will come back to it later.

We are going to create a UICollectionView with custom Cells.

So for that we will first create a class for the Custom Rows in the UICollection.
For that Go to Project->right Click-> Add new File -> Cocoa files -> name it “CustomCollectionCell” and extends UICollectionViewCell

UICollectionView in iOS

CustomCollectionCell.h

#import <UIKit/UIKit.h>

@interface CustomCollectionCell : UICollectionViewCell
{
   
}

@property (nonatomic, strong) IBOutlet UILabel *collectionLabel;
@property (nonatomic, strong) IBOutlet UIImageView *collectionImage;

@end

CustomCollectionCell.m

#import "CustomCollectionCell.h"

@implementation CustomCollectionCell

@end

Now you will notice that there will be a new UICollection row in the hierarchy of the interface in which
the UICollectionView is placed.

UICollectionView in iOS

Now after selecting the cell row from the hierarchy go to the attributes inspector and set the class
name as “CustomCollectionCell” as shown in the Screenshot below.

UICollectionView in iOS

Also set the “identifier” as “CollectionCell”.

UICollectionView in iOS

Now place an “ImageView” and “Label” inside the label and connect it to the variables in the CustomCollectionCell,collectionImage and collectionLabel.

Now we will go to the controller that implements the UICollectionView.

Like TableViews UICollectionView also has delegate methods.

So Add the delegate to the ViewController.h

We will set the Datasource and Delegate in the code itself.

ViewController.h



#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>{
   
    NSArray *image_array, *label_array;
    
}

@property(nonatomic, weak) IBOutlet UICollectionView *collectionView;


@end

In the above code we have a variable for the UICollectionView, so please hook it to the outlet before proceeding otherwise you will see nothing in the interface.

ViewController.m

#import "ViewController.h"
#import "CustomCollectionCell.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize collectionView;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    image_array = [NSArray arrayWithObjects: @"apple.png", @"android.png", @"apple.png", @"android.png",@"apple.png", @"android.png",@"apple.png", @"android.png", nil ];
    label_array = [NSArray arrayWithObjects: @"APPLE", @"ANDROID",@"APPLE", @"ANDROID", @"APPLE", @"ANDROID",
                   @"APPLE", @"ANDROID", nil ];
    
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    CGRect rect = collectionView.frame;
    rect.origin.x = 5;
    rect.origin.y = 0;
    rect.size.width = [[UIScreen mainScreen] bounds].size.width - 5;
    rect.size.height = [[UIScreen mainScreen] bounds].size.height;
    
    collectionView.frame = rect;
    
    collectionView.backgroundColor = [UIColor clearColor];
}


-(void) setBorder:(UIView *) theView withBGColor:(UIColor *) color withCornerRadius :(float) radius andBorderWidth :(float) borderWidth andBorderColor :(UIColor *) bgColor WithAlpha:(float) curAlpha
{
    theView.layer.borderWidth = borderWidth;
    theView.layer.cornerRadius = radius;
    theView.layer.borderColor = [color CGColor];
    UIColor *c = [color colorWithAlphaComponent:curAlpha];
    theView.layer.backgroundColor = 1;
}

#pragma mark - UICollectionView Datasource
// 1
- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section {
    return [image_array count];
}
// 2
- (NSInteger)numberOfSectionsInCollectionView: (UICollectionView *)collectionView {
    return 1;
}
// 3
- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *simpleTableIdentifier = @"CollectionCell";
    
    CustomCollectionCell *cell = [cv dequeueReusableCellWithReuseIdentifier:simpleTableIdentifier forIndexPath:indexPath];
    cell.collectionLabel.text = [label_array objectAtIndex:indexPath.row];
    cell.collectionImage.image = [UIImage imageNamed: [image_array objectAtIndex:indexPath.row]];
    
    if(indexPath.row % 2 == 0)
        [self setBorder:cell withBGColor:[UIColor greenColor] withCornerRadius:3.0 andBorderWidth:0.5 andBorderColor:[UIColor redColor] WithAlpha:1.0];
    else
        [self setBorder:cell withBGColor:[UIColor redColor] withCornerRadius:3.0 andBorderWidth:0.5 andBorderColor:[UIColor redColor] WithAlpha:1.0];
    
    return cell;
}
// 4
/*- (UICollectionReusableView *)collectionView:
 (UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
 {
 return [[UICollectionReusableView alloc] init];
 }*/


#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"Clicked %d", indexPath.row);
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath {

}

#pragma mark – UICollectionViewDelegateFlowLayout

// 1
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGSize s = CGSizeMake([[UIScreen mainScreen] bounds].size.width/2 - 8, [[UIScreen mainScreen] bounds].size.height/2-70);
    return s;
}

// 3
- (UIEdgeInsets)collectionView:
(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(5, 0, 5, 5);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

All done, Just go on and run the application.

You can download the complete source code from here.

What is @property in iOS mean?

The goal of @property directive in iOS is to create the getters and setters for that object so that you can access it in your program. It allows you to specify the behavior of a public property on a semantic level, and it takes care of the implementation details for you.

This article also tells how you can alter these “getters and setters” that are generated by @property

The @property Directive

Let’s see what happens when we declare an @property directive.

Lets study it with an example

 // Car.h
#import <Foundation/Foundation.h>

@interface Car : NSObject

@property BOOL running;

@end
// Car.m
#import "Car.h"

@implementation Car

@synthesize running = _running;    // Optional for Xcode 4.4+

@end

The compiler generates a getter and a setter for the “running” property.
The default naming convention is to use the property itself as the getter, prefix it with set for the setter, and prefix it with an underscore for the instance variable, like so:

- (BOOL)running {
    return _running;
}
- (void)setRunning:(BOOL)newValue {
    _running = newValue;
}

So when you declare a variable using @property this means that you can call its getter and setter as if it is included in the class interface.

You can also override them in Car.m to supply custom getter/setters, but this makes the @synthesize directive mandatory.
However, you should rarely need custom accessors, since @property attributes let you do this on an abstract level.

so when you call

Car *maruti = [Car new];
maruti.running = YES;                // [maruti setRunning:YES]
NSLog(@"%d", maruti.running);        // [maruti running]

You can also change the default getter and setter like this.


@property (getter=isRunning) BOOL running;

Now the “getter” method is called “isRunning” and “setter” method is “setRunning”


Car *maruti = [[Car alloc] init];
maruti.running = YES;                // [maruti setRunning:YES]
NSLog(@"%d", maruti.running);        // [maruti isRunning]
NSLog(@"%d", [maruti running]);      // Error: method no longer exists

The readonly Attribute

When you specify “readonly” attribute to a variable, compiler omits its its setter method but the “getter” is unaffected.


#import <Foundation/Foundation.h>

@interface Car : NSObject

@property (getter=isRunning, readonly) BOOL running;

- (void)startEngine;
- (void)stopEngine;

@end


// Car.m
#import "Car.h"

@implementation Car

- (void)startEngine {
    _running = YES;
}
- (void)stopEngine {
    _running = NO;
}

@end

@property also generates an instance variable for us, which is why we can access _running without declaring it anywhere (we can’t use self.running here because the property is read-only).


Car *maruti = [Car new];
[maruti startEngine];
NSLog(@"Running: %d", maruti.running);
maruti.running = NO;                      // Error: read-only property

The nonatomic Attribute

Atomicity deals with how properties behave in a threaded environment.
When you have more than one thread, it’s possible for the setter and the getter to be called at the same time.
This means that the getter/setter can be interrupted by another operation, possibly resulting in corrupted data.

Using atomic somewhat means that your variable is thread safe.

Properties declared with @property are atomic by default, and this does incur some overhead.

So if we can do like this if you application is not a multithreaded application


@property (nonatomic) NSString *model;

The strong Attribute

The strong attribute creates an owning relationship to whatever object is assigned to the property. This is the implicit behavior for all object properties, which is a safe default because it makes sure the value exists as long as it’s assigned to the property.

Let’s take a look at how this works by creating another class called Person. It’s interface just declares a name property:


// Person.h
#import <Foundation/Foundation.h>

@interface Person : NSObject

@property (nonatomic) NSString *name;

@end


// Person.m
#import "Person.h"

@implementation Person

- (NSString *)description {
    return self.name;
}

@end

Above implementation overrides NSObject’s description method, which returns the string representation of the object.

Now we will add a person to the Car Class


// Car.h
#import <Foundation/Foundation.h>
#import "Person.h"

@interface Car : NSObject

@property (nonatomic) NSString *model;
@property (nonatomic, strong) Person *driver;

@end

Now during usage


Person *hari = [Person new];
hari.name = @"hari";

Car *maruti = [Car new];
maruti.model = @"Maruti Swift";
maruti.driver = hari;

NSLog(@"%@ is driving the %@", maruti.driver, maruti.model);
        

Since driver is a strong relationship, the maruti object takes ownership of john.
This ensures that it will be valid as long as maruti needs it.

The weak Attribute

Strong references pose a problem if, for example, we need a reference from driver back to the Car object he’s driving. First, let’s add a car property to Person.h:


// Person.h
#import <Foundation/Foundation.h>

@class Car;

@interface Person : NSObject

@property (nonatomic) NSString *name;
@property (nonatomic, strong) Car *car;

@end

The @class Car line is a forward declaration of the Car class. It’s like telling the compiler, “The Car class exists, don’t try to find it right now.”

Now use it like this


maruti.driver = hari;
hari.car = maruti;       // Add this line

Now there is a relation b/w maruti and Person and also Person and maruti.
So it is not destroyable by memory management.

This is called a retain cycle, which is a form of memory leak.

But we can fix it by using “weak” attribute like this


@property (nonatomic, weak) Car *car;

The weak attribute creates a non-owning relationship to car.
This allows hari to have a reference to maruti while avoiding a retain cycle.

The copy Attribute

The copy attribute is an alternative to strong. Instead of taking ownership of the existing object, it creates a copy of whatever you assign to the property, then takes ownership of that. Only objects that conform to the NSCopying protocol can use this attribute.

Example


// Car.h
@property (nonatomic, copy) NSString *model;

Now, Car will store a brand new instance of whatever value we assign to model.


Car *maruti = [Car new];
NSMutableString *model = [NSMutableString stringWithString:@"Maruti Swift"];
maruti.model = model;

NSLog(@"%@", maruti.model);
[model setString:@"Maruti Zen"];
NSLog(@"%@", maruti.model);            // Still "Maruti Swift"

The retain Attribute

The retain attribute is the Manual Retain Release version of strong, and it has the exact same effect: claiming ownership of assigned values.
You shouldn’t use this in an Automatic Reference Counted environment.

The assign Attribute

The assign attribute doesn’t perform any kind of memory-management call when assigning a new value to the property.
This is the default behavior for primitive data types, and it used to be a way to implement weak references before iOS 5.
Like retain, you shouldn’t ever need to explicitly use this in modern applications.

Summary

getter= —> Use a custom name for the getter method.
setter= —> Use a custom name for the setter method.
readonly —> Don’t synthesize a setter method, creates only getter method [the trick to make setter method “private” for class users – so only getter method will be visible for compiler. Usually in implementation file this property is redeclared without readonly attribute using custom category so that setter method can be used inside class itself.]
nonatomic —> Don’t guarantee the integrity of accessors in a multi-threaded environment. This is more efficient than the default atomic behavior.
strong —> Create an owning relationship between the property and the assigned value. This is the default for object properties. [synthesized getter method will return ivar directly without locking it for thread-safety]
weak —> Create a non-owning relationship between the property and the assigned value. Use this to prevent retain cycles.
copy —> Create a copy of the assigned value instead of referencing the existing instance.
retain —> Class retains the pointer, the previous value is released

Download an image with ProgressBar in iOS

Hi all,

Today I will show you how you can download an image showing complete progress.

Make sure that you have an interface like the below image.

Download Image IOS Progress

You should link all the interface views with the corresponding variables in ViewController.h

ViewController.h


#import <uikit /UIKit.h>

@interface ViewController : UIViewController <nsurlconnectiondatadelegate>

@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, weak) IBOutlet UIButton   *btn_download;
@property (nonatomic, weak) IBOutlet UILabel   *lbl_download;

@end


ViewController.m



#import "ViewController.h"

@interface ViewController ()

@property (strong, nonatomic) NSURLConnection *connectionManager;
@property (strong, nonatomic) NSMutableData *downloadedMutableData;
@property (strong, nonatomic) NSURLResponse *urlResponse;

@end

@implementation ViewController{
    
#define IMAGE_URL @"http://img1.wikia.nocookie.net/__cb20111229061816/lego/images/b/b8/Ws-space-apple-logo.jpg"
}

- (void)viewDidLoad
{
    [super viewDidLoad];   
}

-(IBAction)downloadImage :(id)sender{
    
    self.btn_download.enabled = NO;
    self.downloadedMutableData = [[NSMutableData alloc] init];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:IMAGE_URL]
                                                cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                            timeoutInterval:60.0];
    self.connectionManager = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

#pragma mark - Delegate Methods
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    NSLog(@"%lld", response.expectedContentLength);
    self.urlResponse = response;
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.downloadedMutableData appendData:data];
    self.progressView.progress = ((100.0/self.urlResponse.expectedContentLength)*self.downloadedMutableData.length)/100;
    
    float per = ((100.0/self.urlResponse.expectedContentLength)*self.downloadedMutableData.length);
    self.lbl_download.text = [NSString stringWithFormat:@"%0.f%%", per];
    
    if (self.progressView.progress == 1) {
        self.progressView.hidden = YES;
        self.btn_download.enabled = YES;
    } else {
        self.progressView.hidden = NO;
    }
    
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    self.imageView.image = [UIImage imageWithData:self.downloadedMutableData];
    self.lbl_download.text = @"Download Complete";
}

@end

You can download the complete source code from here.

Creating a Custom Alert or PopUp in iOS

Custom PopUp IOS

First we will write a class that extends UIView to create a Custom PopUp

Create a Cocoa file and name it CustomPopUp

You should get two files CustomPopUp.h and CustomPopUp.m

CustomPopUp.h


#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@protocol ClickDelegates;

@interface CustomPopUp : UIView{
    
      UIView *childPopUp;
      id<ClickDelegates> _click_delegate;
      UIViewController *_parent;
    
}

@property (nonatomic, retain) id<ClickDelegates> _click_delegate;
@property (nonatomic, retain) UIViewController *_parent;

-(void) initAlertwithParent : (UIViewController *) parent withDelegate : (id<ClickDelegates>) theDelegate;

-(IBAction)OnOKClick :(id) sender;

-(void) hide;

-(void) show;

@end


// Delegate

@protocol ClickDelegates<NSObject>

@optional

-(void) okClicked;
-(void) cancelClicked;

@end

CustomPopUp.m



#import "CustomPopUp.h"
#import "Util.h"

@implementation CustomPopUp{
    
    float popUpX;
    CGRect popUpRect;
}

@synthesize _click_delegate, _parent;


-(void) initAlertwithParent : (UIViewController *) parent withDelegate : (id<ClickDelegates>) theDelegate{
    
    self._click_delegate = theDelegate;
    self._parent = parent;
    
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenWidth = screenRect.size.width;
    CGFloat screenHeight = screenRect.size.height;
    
    CGRect rect = CGRectMake(0, 0, screenWidth, screenHeight);
    self.frame = rect;
    self.backgroundColor = [UIColor clearColor];
    
    childPopUp = [UIView new];
    float popUpHeight = screenHeight/3;
    
    popUpX = 20.0;
    
    popUpRect = CGRectMake(popUpX, (screenHeight - popUpHeight)/2, screenWidth - (popUpX * 2), popUpHeight);
    childPopUp.center = self.center;
    self.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.001, 0.001);
    [self setBorderOnly:childPopUp withBGColor:[UIColor orangeColor] withCornerRadius:5.0 andBorderWidth:0.0 andBorderColor:[UIColor greenColor] WithAlpha:1];
    childPopUp.frame = popUpRect;
    [self addSubview:childPopUp];
  
    [self addLabel];
    
    [self addButton];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.2];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(bounce1AnimationStopped)];
    self.transform = CGAffineTransformScale(CGAffineTransformIdentity, 1.1, 1.1);
    [UIView commitAnimations];
    
}

-(void) show{

    [self._parent.view addSubview:self];
}

-(void) addLabel{
    
    // Add Label
    UILabel *lblForDisplay=[[UILabel alloc]initWithFrame:CGRectMake(popUpX, popUpX, popUpRect.size.width - popUpX, popUpX)];
    lblForDisplay.backgroundColor=[UIColor clearColor];
    lblForDisplay.textColor=[UIColor blackColor];
    lblForDisplay.text=@"This is a custom Alert";
    [childPopUp addSubview:lblForDisplay];
    
}


-(void) addButton{
    
    // Add Button
    UIButton *okBtn = [[UIButton alloc]initWithFrame:CGRectMake(popUpX, childPopUp.frame.size.height - 50, popUpRect.size.width - 40, 40)];
    okBtn.backgroundColor=[UIColor blueColor];
    [self setBorderOnly:okBtn  withBGColor:[UIColor greenColor] withCornerRadius:5.0 andBorderWidth:0.0 andBorderColor:[UIColor greenColor] WithAlpha:1];
    [okBtn setTitle:@"OK" forState:UIControlStateNormal];
    [okBtn addTarget:self action:@selector(OnOKClick:) forControlEvents:UIControlEventTouchDown];
    [childPopUp addSubview:okBtn];
    
}

-(IBAction)OnOKClick :(id) sender{
    
    [_click_delegate okClicked];
    
}

-(void) show : (UIViewController *) parent{
    
}

-(void) hide{
    
    [self removeFromSuperview];
    
}

- (void)bounce1AnimationStopped {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:.2];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(bounce2AnimationStopped)];
    self.transform = CGAffineTransformScale(CGAffineTransformIdentity, 0.9, 0.9);
    [UIView commitAnimations];
}

- (void)bounce2AnimationStopped {
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:.2];
    self.transform = CGAffineTransformIdentity;
    [UIView commitAnimations];
}


-(void) setBorderOnly:(UIView *) theView withBGColor:(UIColor *) color withCornerRadius :(float) radius andBorderWidth :(float) borderWidth andBorderColor :(UIColor *) bgColor WithAlpha:(float) curAlpha
{
    theView.layer.borderWidth = borderWidth;
    theView.layer.cornerRadius = radius;
    theView.layer.borderColor = [color CGColor];
    UIColor *c = [color colorWithAlphaComponent:curAlpha];
    theView.layer.backgroundColor = 1;
}

@end

I have a sample interface like this.

Custom PopUp IOS

Now the ViewController.m



#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController{

    CustomPopUp *mPopUp;
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //create delegate    
    mPopUp = [CustomPopUp new];
    [mPopUp initAlertwithParent:self withDelegate:self];
    
    
}

-(void) okClicked{

    [mPopUp hide];
    
}

-(void) cancelClicked{
    NSLog(@"Cancel");
}

-(IBAction)showAlert :(id)sender{
    [mPopUp show];
}

-(IBAction)dummyClick :(id)sender{
    
    NSLog(@"Click Dummy");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

MAKE SURE YOU HOOK UP THE BUTTONS TO THEIR CORRESPONDING FUNCTIONS.

You can download the complete source code from here.

NSURLConnection – A Simple example – Upload image to server using POST method.

Make sure you setup the server and have gone through this post before reading this article.

You can read more about NSURLConnection Class from here.

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURLConnection_Class/index.html#//apple_ref/occ/instm/NSURLConnection/

Here In this article I am going to select an image from the gallery and upload to a server using

1. Synchronous method
2. Asynchronous method – different ways.

First you have to make an interface like the below screenshot.
5 buttons, 1 Imageview and a label.
Make sure you hook all the controls to their respective labels and corresponding functions.

Upload Image To server using NSURLConnection

Upload Image To server using NSURLConnection

Now to the code.

ViewController.h


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UINavigationControllerDelegate,
UIImagePickerControllerDelegate, NSURLConnectionDelegate>{

    IBOutlet UILabel *response;
    NSMutableData *_responseData;
    
}


@property (strong, nonatomic) IBOutlet UIImageView* imageView;

- (IBAction) pickImage:(id)sender;


@end

ViewController.m


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
{
    NSData *pngData;
    NSData *syncResData;
    NSMutableURLRequest *request;
    UIActivityIndicatorView *indicator;
    
    #define URL            @"http://localhost/UploadImage/Upload_Image.php"  // change this URL
    #define NO_CONNECTION  @"No Connection"
    #define NO_IMAGE      @"NO IMAGE SELECTED"
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    pngData = nil;
    [self initPB];
}

- (IBAction) pickImage:(id)sender{
    
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.delegate = self;
    [self presentViewController:pickerController animated:YES completion:nil];
}

#pragma mark -
#pragma mark UIImagePickerControllerDelegate

- (void) imagePickerController:(UIImagePickerController *)picker
         didFinishPickingImage:(UIImage *)image
                   editingInfo:(NSDictionary *)editingInfo
{
    self.imageView.image = image;
    pngData = UIImagePNGRepresentation(image);
    [self dismissModalViewControllerAnimated:YES];
}

-(BOOL) setParams{
    
    if(pngData != nil){
        
        [indicator startAnimating];
        
        request = [NSMutableURLRequest new];
        request.timeoutInterval = 20.0;
        [request setURL:[NSURL URLWithString:URL]];
        [request setHTTPMethod:@"POST"];
        
        NSString *boundary = @"---------------------------14737809831466499882746641449";
        NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
        [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
        [request setValue:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" forHTTPHeaderField:@"Accept"];
        [request setValue:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/536.26.14 (KHTML, like Gecko) Version/6.0.1 Safari/536.26.14" forHTTPHeaderField:@"User-Agent"];
        
        NSMutableData *body = [NSMutableData data];
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"uploaded_file\"; filename=\"%@.png\"\r\n", @"Uploaded_file"] dataUsingEncoding:NSUTF8StringEncoding]];
        
        [body appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
        
        [body appendData:[NSData dataWithData:pngData]];
        
        [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        
        
        [request setHTTPBody:body];
        [request addValue:[NSString stringWithFormat:@"%d", [body length]] forHTTPHeaderField:@"Content-Length"];
        
        return TRUE;
        
    }else{
        
        response.text = NO_IMAGE;
     
        return FALSE;
    }
}

- (IBAction) uploadImageSync:(id)sender
{
    
    if( [self setParams]){
        
        NSError *error = nil;
        NSURLResponse *responseStr = nil;
        syncResData = [NSURLConnection sendSynchronousRequest:request returningResponse:&responseStr error:&error];
        NSString *returnString = [[NSString alloc] initWithData:syncResData encoding:NSUTF8StringEncoding];
        
        NSLog(@"ERROR %@", error);
        NSLog(@"RES %@", responseStr);
        
        NSLog(@"%@", returnString);
        
        if(error == nil){
            response.text = returnString;
        }
    
        [indicator stopAnimating];
    
    }
    
}

- (IBAction) uploadImageAsync1:(id)sender
{

     if( [self setParams]){
    
        NSOperationQueue *queue = [[NSOperationQueue alloc]init];
        
        // Loads the data for a URL request and executes a handler block on an operation queue when the request completes or fails.
        [NSURLConnection sendAsynchronousRequest:request
                                           queue:queue
                               completionHandler:^(NSURLResponse *urlResponse, NSData *data, NSError *error){
                                   NSLog(@"Completed");
                                   
                                   response.text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                   
                                   [indicator stopAnimating];
                                   [UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
                                   
                                   if (error) {
                                       NSLog(@"error:%@", error.localizedDescription);
                                   }
                                  
                               }];
     }
    

}

- (IBAction) uploadImageAsync2:(id)sender{
    
     if( [self setParams]){
    
         // Returns an initialized URL connection and begins to load the data for the URL request.
         if([[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]){
         
         };
         
     }
    
}

- (IBAction) uploadImageAsync3:(id)sender{
    
    if( [self setParams]){
        
       //Creates and returns an initialized URL connection and begins to load the data for the URL request.
        
        if([NSURLConnection connectionWithRequest:request delegate:self]){
            
        };
    }
    
}

-(void) initPB{
    indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    indicator.frame = CGRectMake(([UIScreen mainScreen].bounds.size.width)/2, ([UIScreen mainScreen].bounds.size.height)/2 , 40.0, 40.0);
    indicator.center = self.view.center;
    [self.view addSubview:indicator];
    [indicator bringSubviewToFront:self.view];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
}

#pragma mark NSURLConnection Delegate Methods

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    // A response has been received, this is where we initialize the instance var you created
    // so that we can append data to it in the didReceiveData method
    // Furthermore, this method is called each time there is a redirect so reinitializing it
    // also serves to clear it
    _responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [_responseData appendData:data];
}

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
                  willCacheResponse:(NSCachedURLResponse*)cachedResponse {
    // Return nil to indicate not necessary to store a cached response for this connection
    return nil;
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now
    
    
    response.text = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding];
    NSLog(@"_responseData %@", response.text);
    
    [indicator stopAnimating];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = FALSE;
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    // The request has failed for some reason!
    // Check the error var
    
    NSLog(@"didFailWithError %@", error);
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

Now we go to the server side.

Please note the server file path in the code.
You must create a directory named “uploads” in the server before running the application.
Also Make sure that your server is running before you execute.

Refer the below Screenshot.

Upload Image To server using NSURLConnection

<?php
$target_path1 = "uploads/";

/* Add the original filename to our target path.
Result is "uploads/filename.extension" */
$target_path1 = $target_path1 . basename( $_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $target_path1)) {
    echo "The file ".  basename( $_FILES['uploaded_file']['name']).
    " has been uploaded to ".$target_path1;;
} else{
    echo "There was an error uploading the file, please try again!";
    echo "filename: " .  basename( $_FILES['uploaded_file']['name']);
    echo "target_path: " .$target_path1;
}
?>

You can download the complete source code from here.

Upload Image To server using NSURLConnection

Select an image from Gallery and show it in an ImageView in ios.

Hey all,

This is a simple post showing how you can open the “Gallery” or “Photos” application in iOS.

The Sample UI should look like this.

Select image from Gallery in ios

Screenshot selecting image from the Gallery.

Select image from gallery in ios

Now to the code.

ViewController.m

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UINavigationControllerDelegate,
UIImagePickerControllerDelegate>


@property (strong, nonatomic) IBOutlet UIImageView* imageView;

- (IBAction) pickImage:(id)sender;


@end

ViewController.m


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (IBAction) pickImage:(id)sender{
    
    UIImagePickerController *pickerController = [[UIImagePickerController alloc]
                                                 init];
    pickerController.delegate = self;
    [self presentViewController:pickerController animated:YES completion:nil];
}

#pragma mark -
#pragma mark UIImagePickerControllerDelegate

- (void) imagePickerController:(UIImagePickerController *)picker
         didFinishPickingImage:(UIImage *)image
                   editingInfo:(NSDictionary *)editingInfo
{
    self.imageView.image = image;
    [self dismissModalViewControllerAnimated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

We add “UINavigationControllerDelegate,UIImagePickerControllerDelegate” to get the events after selecting the image from
the Gallery.

The below function is called after selecting image from Gallery

- (void) imagePickerController:(UIImagePickerController *)picker
didFinishPickingImage:(UIImage *)image
editingInfo:(NSDictionary *)editingInfo

You can download the complete source code from here.

Send Data to server in iOS using POST OR GET – A Simple Example

First Make sure you have this kind of layout and you have linked all the views to their respective variables.

For server side I am using XAMPP for Localhost for now and My php file will be residing in Applications ▸ XAMPP ▸ xamppfiles ▸ htdocs

You can download “XAMPP For Mac” from this link.

When copying this code, make changes according to your server.

iOS Server connection using POST or GET
So I will go directly to the code.

ViewController.h


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<NSURLConnectionDelegate>
{
    IBOutlet UITextField *username, *passsword;
    IBOutlet UILabel *serverResponse;
}

@end

ViewController.m


#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController{
    
    NSMutableData *mutableData;
    
    #define URL            @"http://localhost/test.php"  // change this URL
    #define NO_CONNECTION  @"No Connection"
    #define NO_VALUES      @"Please enter parameter values"
   
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
}

-(IBAction)sendDataUsingPost:(id)sender{
    
    [self sendDataToServer :@"POST"];
   
}

-(IBAction)sendDataUsingGet:(id)sender{
    
    [self sendDataToServer : @"GET"];
}

-(void) sendDataToServer : (NSString *) method{
    
    NSString *usrname  = username.text;
    NSString *pass = passsword.text;
    
    if(usrname.length > 0 && pass.length > 0){
        
        serverResponse.text = @"Getting response from server...";
        
        NSURL *url = nil;
        NSMutableURLRequest *request = nil;
        
        // Only Difference between POST and GET is only in the way they send parameters
        
        if([method isEqualToString:@"GET"]){
            
            NSString *getURL = [NSString stringWithFormat:@"%@?username=%@&password=%@", URL, usrname, pass ];
            url = [NSURL URLWithString: getURL];
            request = [NSMutableURLRequest requestWithURL:url];
            
        }else{  // POST
            
            NSString *parameter = [NSString stringWithFormat:@"username=%@&password=%@",usrname, pass ];
            NSData *parameterData = [parameter dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
;
            url = [NSURL URLWithString: URL];
            request = [NSMutableURLRequest requestWithURL:url];
            [request setHTTPBody:parameterData];
        
        }
        
        [request setHTTPMethod:method];
        [request addValue: @"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
       
        NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
        
        if( connection )
        {
            
            mutableData = [NSMutableData new];
            
        }else{
            
            serverResponse.text = NO_CONNECTION;
            
        }
        
    }else{
        
        serverResponse.text = NO_VALUES;
        
    }
    
}

#pragma mark NSURLConnection delegates

-(void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
    [mutableData setLength:0];
}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [mutableData appendData:data];
}

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    serverResponse.text = NO_CONNECTION;
    return;
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *responseStringWithEncoded = [[NSString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
    //NSLog(@"Response from Server : %@", responseStringWithEncoded);
    NSAttributedString * attrStr = [[NSAttributedString alloc] initWithData:[responseStringWithEncoded dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    serverResponse.attributedText = attrStr;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end


Here is the server side PHP code that can handle both POST and GET Requests.
Since you are getting the values, You can modify this code to say check with the database and
send appropriate result.

Here I am just sending back the values send from the Client Side (From iPhone or any other device)

<?php

	echo" Response From Server Side";

	echo "Username : " .$_REQUEST['username'];
	echo "Password : ".$_REQUEST['password'];
	
        // Do any database operations here...
?>

iOS Server Connection using POST and GET

You can download the complete source code from here.

StoryBoards in iOS – A Simple Example

Hey everyone,

Today we will see how we can use storyboards in an application.

First we will Create a sample project named “StoryBoardDemo”

StoryBoards in iOS, iPhone ,iPad, Apple

StoryBoards in iOS, iPhone ,iPad, Apple

Now we will Add the Navigation Controller
For that Go To Menu -> Editor >Embed In -> NavigationController

StoryBoards in iOS, iPhone ,iPad, Apple

StoryBoards in iOS, iPhone ,iPad, Apple

Now Double Click on the Title Bar and Add the title “Companies”

StoryBoards in iOS, iPhone ,iPad, Apple

Now Drag a table View on to the ViewController.
StoryBoards in iOS, iPhone ,iPad, Apple

Now we will add a prototype cell (a row) in the TableView

Search and Drag a “TableView Cell” inside the TableView.

StoryBoards in iOS, iPhone ,iPad, Apple

Now Select the TableView Prototype Cell and Go to the Attributes Inspector.

Select “Style = Basic”
Identifier = “Company_cell” // This is for referencing each row inside the code.

Now a new Label will appear inside the Prototype Cell.

StoryBoards in iOS, iPhone ,iPad, Apple

Make sure you link “delegate” and “datasource” to the view controller.
Otherwise data will not appear in the tableview.
For that Control Click on the tableView and Drag to the ViewController in the TreeView on
the left.

OK Now we will add another ViewController and add a connection between ViewControllers.

Right Click on the Project Name -> Add New Files > Cocoa touch
[Please UNTICK the checkbox to create the XIB file]

I said to UNTICK the creation of XIB file because we are here to study How STORYBOARD works right?

StoryBoards in iOS, iPhone ,iPad, Apple

So we will add new controller to the storyboard as follows.
Click on the Main.StoryBoard. Go to the Controls section and Search for ViewController and Drag to the storyboard and add a label to it.
You may customise the label you want.

StoryBoards in iOS, iPhone ,iPad, Apple

StoryBoards in iOS, iPhone ,iPad, Apple

Now Do exactly the same step.

Ctrl + Click on the TableView Row(prototype Cell) in the Companies-List ViewController and Drag to DetailsViewController.

Now a window will popup , From that under the “Select Sugue” section click “show”.
Here what we have done is we are telling the controller that when we click on the Tableview Row it should navigate to DetailView Controller.

Next Step Ctrl Click on the Bridge between the ComapniesViewController and DetailViewController, then Go to the attributes inspector on the right.
Give a name for the bridge.

StoryBoards in iOS, iPhone ,iPad, Apple

Now we will go to code

CompaniesViewController.h.

Add the tableview delegates, so that we can get the event on the click of the tableview.

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) IBOutlet UITableView *_tableView;

@end

CompaniesViewController.m

#import "CompaniesViewController.h"
#import "DetailsViewController.h"

@interface ViewController ()

@end

@implementation ViewController{
    NSArray *_companies;
}

@synthesize _tableView;

- (void)viewDidLoad {
    [super viewDidLoad];
    
      _companies = [NSArray arrayWithObjects:@"Apple", @"Google", @"Sony", @"Samsung", @"HTC", nil];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_companies count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *simpleTableIdentifier = @"RecipeCell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }
    
    cell.textLabel.text = [_companies objectAtIndex:indexPath.row];
    return cell;
}

// THIS IS THE FUNCTION THAT GETS CALLED WHEN A LINK BETWEEN
// VIEWCONTROLLERS IS ADDED IN THE STORYBOARD.

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"ShowCompanyDetail"]) {  // This should be the same id as the bridge between controllers.
        NSIndexPath *indexPath = [self._tableView indexPathForSelectedRow];
        DetailsViewController *destViewController = segue.destinationViewController;
        destViewController._companyName = [_companies objectAtIndex:indexPath.row];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end

In the DetailsViewController we will add two variables
one for the Label holding the value and the value itself

Make sure you link the label to the variable

DetailsViewController.h

#import <UIKit/UIKit.h>

@interface DetailsViewController : UIViewController

@property (nonatomic, strong) IBOutlet UILabel *_companyLabel;
@property (nonatomic, strong) NSString *_companyName;



@end

DetailsViewController.m


#import "DetailsViewController.h"

@interface DetailsViewController ()

@end

@implementation DetailsViewController

@synthesize _companyLabel;
@synthesize _companyName;

- (void)viewDidLoad {
    [super viewDidLoad];
    // we set the value passed from the companies view controller to the label
// in the Detailview controller.
    
    _companyLabel.text = _companyName;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

You can download the complete source code from here.

Localhost for Android Emulator and iPhone Simulator.

If you are trying to access a file (PHP or java) residing in your server in your own machine, then
you have to use a specific IP to access it. If it is public, then use the other System’s IP

1. If it is localhost, In Android you use it as

10.0.2.2

The localhost refers to the device on which the code is running, in this case the emulator.

If you want to refer to the computer which is running the Android simulator, use the IP address 10.0.2.2 instead. You can read more from here.

2. If you are trying to access from iOS Simulator use can use

http://localhost:8000/your_path

The iOS Simulator uses the host machine network so you should be able to just use localhost or your machines IP address, whichever IP your web service is listening on.

Open Camera, Take Photo, Save it, Load it – iOS Sample code

This example shows how to Open Camera, Take Photo, Save it, Load it in iOS.

Camera Functions in IOS


Before this make sure that you have two buttons and one imageview in the Interface (image above) and link them to appropriate actions
and variables

ViewController.h”


#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UIImagePickerControllerDelegate>
{
    UIImagePickerController *imagePicker;
    IBOutlet UIImageView *imageView;
}

- (IBAction)showCamera:(id)sender;
- (IBAction)loadImage:(id)sender;

@end


ViewController.m



#import "ViewController.h"

@interface ViewController ()
{
    #define FILE_EXTENSION    @".png"
    #define IMAGE_NAME        @"CameraImage"
}
@end

@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.allowsEditing = YES;
        
    }else{
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Camera Unavailable"
                                                       message:@"Unable to find a camera on your device."
                                                      delegate:nil
                                             cancelButtonTitle:@"OK"
                                             otherButtonTitles:nil, nil];
        [alert show];
        alert = nil;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

- (IBAction)showCamera:(id)sender {
    [self presentViewController:imagePicker animated:YES completion:nil];
}

+(NSString *)documentsPath:(NSString *)fileName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:fileName];
    NSLog(@"%@", fullPath);
    
    return fullPath;
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSString *fileSavePath = [ViewController documentsPath:IMAGE_NAME];
    fileSavePath = [fileSavePath stringByAppendingString:FILE_EXTENSION];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    if (image == nil) {
        image = [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    //This checks to see if the image was edited, if it was it saves the edited version as a .png
    if ([info objectForKey:UIImagePickerControllerEditedImage]) {
        //save the edited image
        NSData *imgPngData = UIImagePNGRepresentation([info objectForKey:UIImagePickerControllerEditedImage]);
        [imgPngData writeToFile:fileSavePath atomically:YES];
        
        
    }else{
        //save the original image
        NSData *imgPngData = UIImagePNGRepresentation([info objectForKey:UIImagePickerControllerOriginalImage]);
        [imgPngData writeToFile:fileSavePath atomically:YES];
        
    }
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)loadImage:(id)sender{
    NSString *path = [NSString stringWithFormat:@"%@%@",[ViewController documentsPath:IMAGE_NAME], FILE_EXTENSION];
    NSData *imgData = [NSData dataWithContentsOfFile:path];
    UIImage *thumbNail = [[UIImage alloc] initWithData:imgData];
    imageView.image = thumbNail;
}

@end

Customizing UITableView using “Prototype Cells” in iOS.

Hi all,

In today’s tutorial we will study how we can customize a UITableView using “Prototype Cells” in iOS which was introduced
in XCode 5.0.

First Create a new Project and Name it “CustomTBLView”.

Now you will get the Main.storyBoard file with other ViewController and Delegate Files.

Open Main.storyBoard and “Drag” a TableView on to it.

Now Drag a “UITableViewCell” on to it. This is the Prototype Cell.

Now our “Main.storyBoard” looks like this.

Prototype Cells in iOS

Now select the tableView cell from the Hierarchy and Go to the “Attributes Inspector” on the right side.

Select Style = ” Basic ”
Indentifier = “list_item_cell”

Now you will see that a “Label” will appear in the cell.
Click on the label and go to “Attributes Inspector” and give tag as “100”.

Prototype Cells in iOS

Here “list_item_cell” is the identifier for each prototype cell.
We will use this identifier to get the cell and populate the items.

[ Make sure you like the “delegate” and “datasource” to the ViewController, otherwise no data will be loaded in
the tableview ]

Our work in the Interface Builder is over.

Now Lets do the coding part

Go to the ViewController.h and paste the delegates and the array

ViewController.h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
    
}

@property (strong, nonatomic) NSMutableArray *_tblData;

@end

Now go to ViewController.m and synthesize the array.

These are the delegate methods

- (NSInteger)numberOfSectionsInTableView: (UITableView *)tableView {
}
- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger)section {
}
- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
}

Now your ViewController.m will look like this.



#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize _tblData;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if (!_tblData) {
        _tblData = [[NSMutableArray alloc] initWithObjects:@"iPhone", @"Android", @"Windows", @"Apple", @"Google", @"Microsoft", nil];
    }

}

- (NSInteger)numberOfSectionsInTableView: (UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView: (UITableView *)tableView numberOfRowsInSection: (NSInteger)section {
    
    return [_tblData count];

}

- (UITableViewCell *)tableView: (UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath {
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"list_item_cell"];
    UILabel *lblName = (UILabel *)[cell viewWithTag:100];
    [lblName setText:[_tblData objectAtIndex:[indexPath row]]]; return cell;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end

OK Done. Run the project.

Prototype Cells in iOS

Handling Files in iOS

Hi All,

In Todays article we will see how we can handle files in Objective C.

The list of the methods used for accessing and manipulating files are listed below. Here you have to replace the FilePath1, FilePath2 and FilePath strings to our required full file paths to get the desired action.

NSFileManager *fileManager = [NSFileManager defaultManager];
 //Get documents directory
 NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains
 (NSDocumentDirectory, NSUserDomainMask, YES);
 NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0];
 if ([fileManager fileExistsAtPath:@""]==YES) {
           NSLog(@"File exists");
 } 

Comparing two file contents

 if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) {
         NSLog(@"Same content");
 }

Check if writable, readable and executable

 
 if ([fileManager isWritableFileAtPath:@"FilePath"]) {
         NSLog(@"File isWritable");
 }

  if ([fileManager isReadableFileAtPath:@"FilePath"]) {
          NSLog(@"File isReadable");
 }


 if ( [fileManager isExecutableFileAtPath:@"FilePath"]){
          NSLog(@"File is Executable");
 }

Move file

 if([fileManager moveItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]){
          NSLog(@"File Moved successfully");
 }

Copy file

 
if ([fileManager copyItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]) {
          NSLog(@"File Copied successfully");
 }

Remove file

 if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) {
          NSLog(@"File Removed successfully");
 }

Read file

 NSData *data = [fileManager contentsAtPath:@"Path"];

Write file

 [fileManager createFileAtPath:@"" contents:data attributes:nil];

How to add info button to right side or leftside of navigationbar in iPhone?


    UIButton* infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
    [infoButton addTarget:self action:@selector(showInfoView:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton];

Adding button action function.

- (IBAction)showInfoView:(id)sender {
    
}

Random Integer array without repetition in Objective C Iphone

This sample code generates a random number and checks whether its already present in the array.
If yes then it will not add else it will add, thus generating a random array without duplicates.

-(NSMutableArray *) generateRandomArray : (int) max{
    NSMutableArray *randArray = [NSMutableArray new];
    for (int k = 0; k < max; k++) {
       int r = arc4random() % max;
        if([randArray containsObject:[NSString stringWithFormat:@"%d", r]]){
            k--;
        }else{
            [randArray addObject:[NSString stringWithFormat:@"%d", r]];
        }
    }
    NSLog(@"RAND %@",randArray);
    return randArray;
}

Please leave your valuable comments if you found this post useful.

How to download an image from a URL in Objective C iPhone?

Download image from URL in iPhone

This method downloads the image from the specified URL and stores in the documents directory and then shown in an ImageView.
Make sure you have an imageview linked with the outlet in the UserInterface.


-(void) downloadImageFromURL :(NSString *)imageUrl{
    
    NSURL  *url = [NSURL URLWithString:imageUrl];
    NSData *urlData = [NSData dataWithContentsOfURL:url];
    if ( urlData )
    {
        NSLog(@"Downloading started...");
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"dwnld_image.png"];
        NSLog(@"FILE : %@",filePath);
        [urlData writeToFile:filePath atomically:YES];
        UIImage *image1=[UIImage imageWithContentsOfFile:filePath];
        imageView.image=image1;
        NSLog(@"Completed...");
    }
    
}

Please leave your comments if you found this code useful.

How to create a radioGroup in Android inside a Scrollview?

Here is a sample code that creates a radiobutton group inside a scrollview.
Please make sure you have a scrollview in your UI and its linked.

// This function adds the radio buttons inside the scrollview.
Here I am using some of my variables to generate the count of radio buttons.
Please make sure to change it before using it in your code.

UIRadioButton implementation in iPhone
UIRadioButton implementation in iPhone


NSString *const CHECKED_IMAGE = @"radiochecked.png";
NSString *const UNCHECKED_IMAGE = @"radiounchecked.png";

int y=0;
    
    for(int optionCount = 0; optionCount < [pracObj.answers count]; optionCount++){
        
        UIButton *answerCheckBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [answerCheckBtn addTarget:self action:@selector(answerSelected:)
                                       forControlEvents:UIControlEventTouchDown];
        [answerCheckBtn setTitle:@"" forState:UIControlStateNormal];
        
        //set background image for button
        answerCheckBtn.backgroundColor = [UIColor clearColor];
        answerCheckBtn.frame = CGRectMake(1.0, y+2, 20,20);
        UIImage *buttonImageNormal = [UIImage imageNamed:UNCHECKED_IMAGE];
        UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
        [answerCheckBtn setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
        
        answerCheckBtn.tag = optionCount + ANSWERTAG_STARTING;
        
        UILabel *answerLabel = [UILabel new];
        answerLabel.tag =  optionCount+100;
        answerLabel.text = [[pracObj.answers objectAtIndex:optionCount] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
        answerLabel.lineBreakMode = NSLineBreakByWordWrapping;
        answerLabel.numberOfLines = 1;       
        answerLabel.frame = CGRectMake(30, y+2, 300.0, 20.0);
        
        [answerLabel sizeToFit];
        y+=answerLabel.frame.size.height;
        
        [answerLabel setFont:[UIFont systemFontOfSize:10]];
        [answersScrollView addSubview:answerCheckBtn];
        [answersScrollView addSubview:answerLabel];
    }

And click of each radio button you can cal this function to reset the image.


-(IBAction)answerSelected:(id)sender
{
    UIButton *curBtn = (UIButton*) sender;
    NSLog(@"DYN MEthod Clckd %d", curBtn.tag);
    
    UIImage *buttonImageNormal = [UIImage imageNamed:CHECKED_IMAGE];
    UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
    [curBtn setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
    
    
    [self clearButtons:curBtn.tag];
}

-(void) clearButtons:(int) curTag
{
    int totalAnsCount = [curPracticeQuestionObj.answers count];
    
    for (int y = ANSWERTAG_STARTING; y < (ANSWERTAG_STARTING + totalAnsCount); y++) {
        if (y != curTag) {
            
            UIButton *otherButton = (UIButton *)[answersScrollView viewWithTag:y];
            UIImage *buttonImageNormal = [UIImage imageNamed:UNCHECKED_IMAGE];
            UIImage *strechableButtonImageNormal = [buttonImageNormal stretchableImageWithLeftCapWidth:12 topCapHeight:0];
            [otherButton setBackgroundImage:strechableButtonImageNormal forState:UIControlStateNormal];
            
        }
    }
    
}

How to split a string using a delimiter in iPhone and add it to a mutable array?

Here is a simple code that does this..

-(NSMutableArray *) getAnswers :(NSString *) yourstring{
    NSMutableArray *answers = [NSMutableArray new];
    NSArray *parts = [[yourstring componentsSeparatedByString:@","];
    for(NSString *str in parts){
        [answers addObject:str];
    }
    NSLog(@"RET answers %@", answers);
    return answers;
}

After splitting the string with “componentsSeparatedByString” the parts are added to a NSMutableArray using addObject.

Apple fined by China court for copyright violation

A court in China has ordered Apple to pay compensation to eight Chinese writers and two companies for violating their copyrights.

They had claimed that unlicensed electronic versions of their books had been sold on Apple’s online store.

The court ordered Apple to pay them 1.03m yuan ($165,000; £100,000) in compensation, according to the official news agency Xinhua.
… Read more from here.

http://www.bbc.co.uk/news/business-20856199

How to find your Google Plus ID

This is so simple

1. Go to your Google + account (https://plus.google.com/).

2. Click on the Profile icon on the Left.

3. If you look at the URL in the address bar, it should look something like this:

https://plus.google.com/104653270154306099169/posts

4. The long numerical string in the URL is your Google+ ID. Here is CoderzHeaven’s from the URL above:

104653270154306099169/

Google + CoderzHeaven

How to move a body manually in Box2D? or Give a force to a body in Box2D, iPhone.

This is a sample code to move a body in Box2D .
First you have to make a body with variable name “moving_rec” and call the below function in a schedular at regular intervals.

-(void) moveBody{
       b2Vec2 force = b2Vec2(0,0);
       force = b2Vec2(0,3);       //Giving the x an y to negative will move the body in opposite direction.
       moving_rec->SetLinearVelocity(force); //set Linear velocity for moving in a constant speed.
}

Please leave your comments on this post.

Pause And Resume iPhone Game Using Cocos2D

More than usually we need to apply the functions of Pause and Resume/Play for our games. In Mac’s cocos2D programming it’s more than simple. Simply use the following code for Pause & Resume where ever you want!

/*For Pausing the game*/

[[CCDirector sharedDirector] pause];
[self pauseSchedulerAndActions]; //Call for pausing all schedulers and actions

/*For Resuming/Playing back the game*/

[[CCDirector sharedDirector] resume];
[self resumeSchedulerAndActions]; // Call for resuming all schedulers and actions

:)

Collision detection in Box2D

Hi,

Collision can be detected simply using the following lines of code with box2D.

if((contact.fixtureA == aimFixture && contact.fixtureB == tarFixture) ||
     (contact.fixtureA == tarFixture&& contact.fixtureB == aimFixture ))
     {
        NSLog(@"Collision between aim fixture and target fixture detected!");
     }

Here aimFixture & tarFixture are two custom fixtures whose collision you want to find out.

:)

Using of CCWaves in iPhone

CCWaves is one of the interesting functionalities in Cocos2D iphone.
Check out this following snippet to see how it works.

id my_wavesAction = [CCWaves actionWithWaves:7 amplitude:25 horizontal:NO
                                                               vertical:YES grid:ccg(15,10) duration:10];
[my_sprite runAction: [CCRepeatForever actionWithAction:my_wavesAction n]];

Please leave your valuable comments on this post………………….