Wednesday, November 6, 2013

jSON Parsing for array of dictionaries in iOS

Class created by me for jSON parsing.
iOS developers, this class has method to parse (array of dictionaries).
Feel free to update the class for other type of JSON response strings as well.


https://github.com/ashish9855/jsonParsing


Tuesday, October 22, 2013

Delegate Design Pattern in iOS

About: -

Suppose there is message passing between two objects X, Y.
Suppose an employee and a boss, when employee finishes his task and he has to inform boss about that how would it do?

This is possible in terms of delegate. When X and Y are two objects like employee and boss and as soon as X finishes its task Y is told about it.

Features: -

1.     The main thing is reducing the interdependency of classes.
2.     To make the class more reusable.
3.     Al l the methods of delegate are in protocol, where the person can set required or optional.
4.     Required are compulsory for the delegate to implement.
5.     Optional are not compulsory for the delegate to implement.

Below is the link of git repository to download the delegate sample code: -


Have fun.. !!! Any problems post in comments.

Sunday, September 22, 2013

Creating dynamic scroll view of iOS

This  would create a scroll view which would be divided into two parts in the view.
The images would automatically change there size and adjust there frames accordingly.
This would also have a name below it as well which would adjust according to the image.

You can download the project from here :-

https://bitbucket.org/ashish9855/oscroll

Sunday, August 18, 2013

error in ASIHTTPRequest

This  is a very common error you would face.

You have to include a bundle which is as: libxml2.dylib. 

Go to project Build settingd search for Header Search Paths

and double click and add:-  $(SDKROOT)/usr/include/libxml2


It would work fine.

Creating Asynchronous request for Soap WebService with ASIHTTPRequest

Follow the steps below: -

1) Visit: - http://allseeing-i.com/ASIHTTPRequest/Setup-instructions

Go to this link and download classes which are as told.

2) Read this code for easy understanding:- 

//
//  demoViewController.m
//  SendAsynchronousRequest
//
//  Created by Ashish on 8/17/13.
//  Copyright (c) 2013 ashish. All rights reserved.
//

#import "demoViewController.h"
#import "ASIHTTPRequest.h"
#import "ASIHTTPRequestDelegate.h"
#import "ASINetworkQueue.h"
#import "ASIFormDataRequest.h"

@interface demoViewController ()

@end


@implementation demoViewController

NSMutableString *getData;
NSMutableString *getData1;
NSMutableString *getData2;

//XML Parser
//---xml parsing---
NSXMLParser *xmlParser;
NSMutableString *soapResults;
BOOL elementFound;
int flag;
NSMutableData *webData;


@synthesize activity,MainCatId;

-(void)connectionString
{
   
    [activity startAnimating];
   
    NSURL *url=[NSURL URLWithString:@""];
   
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
   
    [request setDelegate:self];
   
    [request setRequestMethod:@"POST"];
   
    [request addRequestHeader:@"Content-Type" value:@"text/xml"];
   
    [request addRequestHeader:@"SOAPAction" value:@"http://tempuri.org/Search"];
   
    NSString *soapString=[NSString stringWithFormat:
                          @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
]";
    NSLog(@"%@",soapString);
  
   

    NSString *msgLength =[NSString stringWithFormat:@"%d", [soapString length]];
   
    [request addRequestHeader:@"Content-Length" value:msgLength];
   
    [request appendPostData:[soapString dataUsingEncoding:NSUTF8StringEncoding]];
   
    [request setDelegate:self];
   
    [request setDidFinishSelector:@selector(requestDone:)];
   
    [request setDidFailSelector:@selector(requestWentWrong:)];
   
    [request startAsynchronous];
   
   
    if (request)
    {
        webData = [NSMutableData data];
       
        //NSLog(@"response= %@",responseData);
    }

   
   
}


-(void)parseUser:(NSString *)xml{
   
   
    NSData* data=[xml dataUsingEncoding:NSUTF8StringEncoding];
   
    xmlParser = [[NSXMLParser alloc] initWithData:data];
    [xmlParser setDelegate:self];
    [xmlParser setShouldProcessNamespaces:NO];
    [xmlParser setShouldReportNamespacePrefixes:NO];
    [xmlParser setShouldResolveExternalEntities:NO];
    [xmlParser parse];
   
}


# pragma mark View Connection Functionalities

-(void) connection:(NSURLConnection *) connection
didReceiveResponse:(NSURLResponse *) response {
    [webData setLength: 0];
    // NSLog(@"didReceiveResponse");
}

-(void) connection:(NSURLConnection *) connection
    didReceiveData:(NSData *) data {
    [webData appendData:data];
    //NSLog(@"didReceiveData");
}


-(void) parser:(NSXMLParser *) parser
didStartElement:(NSString *) elementName
  namespaceURI:(NSString *) namespaceURI
 qualifiedName:(NSString *) qName
    attributes:(NSDictionary *) attributeDict {
   
    //    CurrentElement = [elementName copy];
    //    NSUserDefaults *userdefaults=[NSUserDefaults standardUserDefaults];
   
    NSLog(@"Element name %@%@",elementName,soapResults);
   
    if( [elementName isEqualToString:@"NewDataSet"])      //enter the tag you want to start
    {
        if (!soapResults)
        {
            soapResults = [[NSMutableString alloc] init];
        }
        elementFound = true;
    }
   
}

-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
{
    if(elementFound)
    {
       
        soapResults = (NSMutableString *) [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        NSLog(@"soap results %@",soapResults);
    }
   
   
}

-(void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
 namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
   
    if([elementName isEqualToString:@""])
    {
        [arr1 addObject:soapResults];

    }
   
    if([elementName isEqualToString:@""])
    {
        [arr2 addObject:soapResults];
        }
   
    if([elementName isEqualToString:@""])
    {
        [arr3 addObject:soapResults];

    }
      
}


- (void)requestDone:(ASIHTTPRequest *)request{
   
    NSString *response = [request responseString];
   
    NSLog(@"%@",response);
   
    [self parseUser:response];
   
              
       
        [activity stopAnimating];
       
        activity.hidden=TRUE;
       
    }
   

- (void)requestWentWrong:(ASIHTTPRequest *)request

{
    NSError *error = [request error];
   
    NSLog(@"%@",error);
   
}


- (void)viewDidLoad
{
    [super viewDidLoad];
   

    [self connectionString];
   
    // Do any additional setup after loading the view, typically from a nib.
}

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

@end


Monday, August 12, 2013

create your ideas into reality

What are you waiting for.. 

Stop spending more time , money, resources.
Just Contact :- a.maheshwari9855@gmail.com
and turn your ideas into reality. 

Platforms:- iOS, Windows Phone, .Net (softwares, Websites)

We wont let you and your idea down. It is as important for us as much as for you.

College startups a great opportunity for you, your ideas will be live without spending much.

We would assist you at every point.

College final year projects: why waste your time in searching on the internet when you can get the full fledged stuff here. With the documentation. 
Do smart work and score smartly.

Convert your ideas into reality

What are you waiting for.. 

Stop spending more time , money, resources.
Just Contact :- a.maheshwari9855@gmail.com
and turn your ideas into reality. 

Platforms:- iOS, Windows Phone, .Net (softwares, Websites)

We wont let you and your idea down. It is as important for us as much as for you.

College startups a great opportunity for you, your ideas will be live without spending much.

We would assist you at every point.

College final year projects: why waste your time in searching on the internet when you can get the full fledged stuff here. With the documentation. 
Do smart work and score smartly.

Saturday, August 10, 2013

Using TextField as UISearchBar and searching UIScrollView

The most awaited post I am writing . I solved as it was not available on the internet.

In demo.xib (.xib file) :-


Just add a textfield. And assign this text field to txt1.

In demo.h ( .h file):- 

//
//  ViewController.h
//  demo
//
//  Created by Ashish Maheshwari on 09/08/13.
//  Copyright (c) 2013 Ashish Maheshwari. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UITextFieldDelegate>

{
       IBOutlet UITextField *txt1;
    
    UIScrollView *scrollView;
    UIScrollView *scrollView1;
    
    // creating a search string
    
    NSString *strSearchData;
    
    // Creating arrays for the data 
    
    NSMutableArray *arr1;
    NSMutableArray *arr2;
    NSMutableArray *arr3;
    
    // mutable arrays to be used during search
    
    NSMutableArray *resultArrayId;
    NSMutableArray *resultArrayName;
    NSMutableArray *resultArrayImage;
    
    // creating dictionaries
    
    NSDictionary *dict1;
    NSDictionary *dict2;
    NSMutableDictionary *dict3;
    
    // creating arrays so that the data can be loaded on load in two images
    
    NSMutableArray *divideSuperId1;
    NSMutableArray *divideSuperId2;
    NSMutableArray *divideSuperImage1;
    NSMutableArray *divideSuperImage2;
    NSMutableArray *divideSuperName1;
    NSMutableArray *divideSuperName2;

}

@property(nonatomic,retain)NSMutableArray *resultArrayId;
@property(nonatomic,retain)NSMutableArray *resultArrayName;
@property(nonatomic,retain)NSMutableArray *resultArrayImage;
@property(nonatomic,retain)IBOutlet UITextField *txt1;
@property(nonatomic,retain)NSString *strSearchData;

@end

In demo.m (.m file):- 

//
//  ViewController.m
//  demo
//
//  Created by Ashish Maheshwari on 09/08/13.
//  Copyright (c) 2013 Ashish Maheshwari. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize resultArrayId,resultArrayImage,resultArrayName,strSearchData,txt1;

# pragma mark Generate Scroll View

-(void)Scroll:(NSMutableArray *)array1 name:(NSMutableArray *)array2 image:(NSMutableArray *)array3
{
    // dividing of array in two parts and showing on load
    
    [divideSuperId1 removeAllObjects];
    [divideSuperId2 removeAllObjects];
    [divideSuperImage1 removeAllObjects];
    [divideSuperImage2 removeAllObjects];
    [divideSuperName1 removeAllObjects];
    [divideSuperName2 removeAllObjects];
    
    
    NSLog(@"arr1= %@",array1);
    NSLog(@"arr2= %@",array2);
    NSLog(@"arr3= %@",array3);
    
    for (int i=0; i < [array1 count]; i=i+1) {
        double cnt=[array1 count];
        if (i < cnt/2) {
            [divideSuperId1 addObject:[array1 objectAtIndex:i]];
        }
        else {
            [divideSuperId2 addObject:[array1 objectAtIndex:i]];
        }
    }
    
    for (int i=0; i < [array3 count]; i=i+1) {
        double cnt=[array3 count];
        if (i < cnt/2) {
            [divideSuperImage1 addObject:[array3 objectAtIndex:i]];
        }
        else {
            [divideSuperImage2 addObject:[array3 objectAtIndex:i]];
        }
    }
    
    for (int i=0; i < [array2 count]; i=i+1) {
        double cnt=[array2 count];
        if (i < cnt/2) {
            [divideSuperName1 addObject:[array2 objectAtIndex:i]];
        }
        else {
            [divideSuperName2 addObject:[array2 objectAtIndex:i]];
        }
    }

  
    
    scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(5, 90,self.view.frame.size.width ,self.view.frame.size.height)];
    
    //    int numberOfImages = 5;
    CGFloat currentY1 = 0.0f;
    CGFloat currentY2 =0.0f;
    
    CGFloat lbCurrentY=0.0f;
    
    CGFloat h1;
    CGFloat h2;
    
    
    for (int i=0; i<[divideSuperId1 count]; i++)
    {
        
        // create image no. 1
        
       
        UIImage *image = [UIImage imageNamed:[divideSuperImage1 objectAtIndex:i]];
        UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
        
        
        CGRect rect = imageView.frame;
        CGFloat width=152;
        CGFloat height=imageView.frame.size.height/2.0;
        rect = CGRectMake(0, currentY1, width, height);
        imageView.frame = rect;
        
        // update currentY
        
        currentY1 += imageView.frame.size.height+5;
        h1=imageView.frame.size.height;
        
        //Puting image on Button 1
        UIButton *btnimage1=[UIButton buttonWithType:UIButtonTypeCustom];
        btnimage1.frame=rect;
        [btnimage1 setImage:imageView.image forState:UIControlStateNormal];
        btnimage1.tag=[[divideSuperId1 objectAtIndex:i]integerValue];
        NSLog(@"%d",btnimage1.tag);
       // [btnimage1 addTarget:self action:@selector(Click:)forControlEvents:UIControlEventTouchUpInside];
        
        // setting label of the first image
        
        NSString *lbname1=[divideSuperName1 objectAtIndex:i];
        UILabel *label;
        CGFloat lbWidth=width;
        CGFloat lbHeight=30;
        lbCurrentY=h1-30;
        
        label=[[UILabel alloc]initWithFrame:CGRectMake(0, lbCurrentY, lbWidth, lbHeight)];
        label.text=lbname1;
        label.textColor=[UIColor whiteColor];
        label.backgroundColor=[UIColor blackColor];
        label.alpha=0.4;
        label.textAlignment=NSTextAlignmentRight;
        [btnimage1 addSubview:label];
        [scrollView addSubview:btnimage1];
    }
    // ----------------------------------------------------------------------------
    
    
    //Create the image No. 2
    
    for(int i=0;i<[divideSuperId2 count];i++)
    {
        CGFloat lbCurrentY2=0.0f// setting the label Y axis
        
        // making image 2
     
        UIImage *image = [UIImage imageNamed:[divideSuperImage2 objectAtIndex:i]];
        UIImageView *imageView2 = [[UIImageView alloc] initWithImage:image];
        
        // frame size of image 2
        
        CGRect rect2=imageView2.frame;
        CGFloat width2=152;
        CGFloat height2=imageView2.frame.size.height/2.0;
        rect2=CGRectMake(width2+3,currentY2, width2,height2);
        imageView2.frame=rect2;
        
        currentY2+=imageView2.frame.size.height+5;
        h2=imageView2.frame.size.height;
        
        // fixing button woith image
        
        UIButton *btnImage2=[UIButton buttonWithType:UIButtonTypeCustom];
        btnImage2.frame=rect2;
        [btnImage2 setImage:imageView2.image forState:UIControlStateNormal];
        btnImage2.tag=[[divideSuperId2 objectAtIndex:i]integerValue];
        NSLog(@"%d",btnImage2.tag);
       // [btnImage2 addTarget:self action:@selector(Click:)forControlEvents:UIControlEventTouchUpInside];
        // making label 2
        
        NSString *labelName=[divideSuperName2 objectAtIndex:i];
        UILabel *label1;
        CGFloat lbwidth2=width2;
        CGFloat lbHeight=30;
        lbCurrentY2=height2-30;
        label1=[[UILabel alloc]initWithFrame:CGRectMake(0,lbCurrentY2,lbwidth2, lbHeight)];
        label1.text=labelName;
        label1.textColor=[UIColor whiteColor];
        label1.backgroundColor=[UIColor blackColor];
        label1.alpha=0.4;
        label1.textAlignment=NSTextAlignmentRight;
        [btnImage2 addSubview:label1];
        [scrollView addSubview:btnImage2];
    }
    
    
    scrollView.contentSize = CGSizeMake(151*2,currentY1+h1);
    
    
    //
    scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
    [self.view addSubview:scrollView];
    
}

-(void)searchScroll
{
        for (NSString *sTemp in arr2)
        {
            
            NSComparisonResult result = [sTemp compare:self.strSearchData options:(NSCaseInsensitiveSearch|NSDiacriticInsensitiveSearch) range:NSMakeRange(0, [self.strSearchData length])];
            
            if (result == NSOrderedSame)
            {
                [resultArrayName addObject:sTemp];
            }
        }
    
    for(int i=0;i<[resultArrayName count];i++)
    {
        [resultArrayId addObject:[dict3 objectForKey:[resultArrayName objectAtIndex:i]]];
       
    }
    
    // getting image
    for(int i=0;i<[resultArrayId count];i++)
    {
        [resultArrayImage addObject:[dict2 objectForKey:[resultArrayId objectAtIndex:i]]];
       }

    NSArray *temp=[scrollView subviews];
    for(UIView *vi in temp)
    {
        [vi removeFromSuperview];
    }
    
    [self Scroll:resultArrayId name:resultArrayName image:resultArrayImage];
    
}

- (BOOL)textFieldShouldReturn:(UITextField *)txt1
{
    [txt1 resignFirstResponder];
    return YES;}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
    {
  
    if([resultArrayId count]>0)
    {
        [resultArrayId removeAllObjects];
    }
     if([resultArrayName count]>0)
    {
        [resultArrayName removeAllObjects];
    }
    if([resultArrayImage count]>0)
    {
        [resultArrayImage removeAllObjects];
    }
    
    if([string length]==0)
    {
        NSArray *temp=[scrollView subviews];
        for(UIView *vi in temp)
        {
            [vi removeFromSuperview];
        }
        [self Scroll:arr1 name:arr2 image:arr3];
    }
        
    if([string length]>0)
    {
        self.strSearchData=[NSString stringWithFormat:@"%@%@",txt1.text,string];
        
        [self searchScroll];
    }
    else{
        NSArray *temp=[scrollView subviews];
        for(UIView *vi in temp)
        {
            [vi removeFromSuperview];
        }
    }
    

    
    return YES;
}

// method for dictionary

-(void)createDictionary

{
  //  NSDictionary *dict1;
    dict1=[NSDictionary dictionaryWithObjects:arr2 forKeys:arr1];
    
   // NSDictionary *dict2;
    dict2=[NSDictionary dictionaryWithObjects:arr3 forKeys:arr1];
    
   // NSDictionary *dict3;
    dict3=[NSDictionary dictionaryWithObjects:arr1 forKeys:arr2];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // allocating arrays
    
    arr1=[[NSMutableArray alloc]initWithObjects:@"1",@"2",@"3",@"4",@"5",@"6", nil];
    arr2=[[NSMutableArray alloc]initWithObjects:@"asd",@"bsd",@"csd",@"dsd",@"asgh",@"asfg",nil];
    arr3=[[NSMutableArray alloc]initWithObjects:@"img1.jpg",@"img2.jpg",@"img3.jpg",@"img4.jpg",@"img4.jpg",@"img3.jpg", nil];
    
 // here we divide the arrays so that the on load scroll view shows all the data
    
    divideSuperId2=[[NSMutableArray alloc]init];
    divideSuperId1=[[NSMutableArray alloc]init];
    
    divideSuperImage1=[[NSMutableArray alloc]init];
    divideSuperImage2=[[NSMutableArray alloc]init];
    
    divideSuperName1=[[NSMutableArray alloc]init];
    divideSuperName2=[[NSMutableArray alloc]init];

    // allocating arrays that get during search
    
    resultArrayId=[[NSMutableArray alloc]init];
    resultArrayName=[[NSMutableArray alloc]init];
    resultArrayImage=[[NSMutableArray alloc]init];
    
    // assiging delegate to text field
    
    txt1.delegate=self;
    
    // create dictionaries with array
    
    [self createDictionary];

    // scroll calling on loada
    
    [self Scroll:arr1 name:arr2 image:arr3];
    
// Do any additional setup after loading the view, typically from a nib.
}

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

@end




Thursday, August 8, 2013

Make a tab bar controller and attach images and text to the items and also navigate to different controllers in iOS


Create a tab bar first:-     

UitabBarController *tabBars;

tabBars= [[UITabBarController alloc] init];

This View Controller will show a tab bar with two items and navigation to different pages:-


    ViewController1 *mjCat=[[ViewController1 alloc]initWithNibName:@"ViewController1" bundle:nil];
    UINavigationController *Browsing1=[[UINavigationController alloc]initWithRootViewController:mjCat];
    mjCat.tabBarItem.title=@"Browse";
    mjCat.tabBarItem.tag=1;
    mjCat.tabBarItem.image=[UIImage imageNamed:@"browse.ico"];
    
    ViewController2 *exCat=[[ViewController2 alloc]initWithNibName:@"ViewController2" bundle:nil];
    UINavigationController *Browsing2=[[UINavigationController alloc]initWithRootViewController:exCat];
    exCat.tabBarItem.title=@"Explore";
    exCat.tabBarItem.tag=2;
    exCat.tabBarItem.image=[UIImage imageNamed:@"explore.ico"];
    
    

    [tabBars setViewControllers:[NSArray arrayWithObjects:majorBrowsing,exploreBrowsing, nil]];
    
    [self.navigationController pushViewController:tabBars animated:YES];
  

Tuesday, August 6, 2013

Navigate on clicking the tab bar item

Here I have explained that how to navigate on clicking tab bar item:-

1) In .h file add UITab bar Delegate :-


@interface StylistViewController : UIViewController<UITabBarDelegate,UITabBarControllerDelegate>
{
     
    IBOutlet UITabBar *bottomBar;
}

@property(nonatomic,retain)UITabBar *bottomBar;

2) On delegate assign delegate to self :- 



- (void)viewDidLoad
{
    [super viewDidLoad];
    
    bottomBar.delegate=self;
}


3) This is a delegate of UITab bar :-

Assign every item you add on tab bar a tag in properties -


- (void)tabBar:(UITabBar *)bottomBar didSelectItem:(UITabBarItem *)item
{
  
    NSUInteger getTagOfTabBr=item.tag;
    NSLog(@"%d",getTagOfTabBr);
    switch (getTagOfTabBr) {
        case 1:
        {
           Category *major=[[Category alloc]initWithNibName:@"Category" bundle:nil];
            [self.navigationController pushViewController:major animated:YES];

            break;
        }
        default:
            break;
    } 
}

Monday, August 5, 2013

Detecting different button clicks in xcode

Here i have explained how you can detect which button is clicked:- 

1) Assign tag to every button in the properties of button.

2) create an IBAction and attach to every button.

-(IBAction)Click:(id)sender
{
   NSLog(@"%d",[sender tag]);
}


3) whenever you click a button it would print its tag.

Transfer your tag to next page: 

 -(IBAction)Click:(id)sender
{
    Main *subCat=[[Category alloc]initWithNibName:@"Category" bundle:nil];
    subCat.getCatVal=[sender tag];
    [self.navigationController pushViewController:subCat animated:YES];
}

// this would assign the tag to the next page getCatVal variable.

Wanna use selecto to call that you can write:-

 UIButton *btnImage2=[UIButton buttonWithType:UIButtonTypeCustom];
 [btnImage2 addTarget:self action:@selector(Click:)forControlEvents:UIControlEventTouchUpInside];