Saturday, 21 February 2015

Sharing using SLComposeViewController

Sharing using SLComposeViewController



Hi Friends !!!  Here I am Trying My Best  for  how To share Image, URL andString In Facebook and Twitter with the help of SLComposeViewController. So,I think its may be very helpful to you,Because here I am Trying so simple & easy  language and method so that everyone can understand it very quickly.


 1 . ShareFile.h and ShareFile.m both files are given below. so download it from given below link and drag and drop in your project (keep both the copy of that file) . 

1)  Sharefile.h       Click Here :-    
2)  Sharefile.m     Click Here  :-     







2. Add below two framework in your project. (Click on Targets ->your app name -> and then the "Build Phase " tab. "Expand 'LinkBinary with Libraries" click the + button in the bottom left of the "Link Binary with Libraries" selection")
    -Accounts.framework
    -Social.framework

3. After adding above two framework now import ShareFile.h file. in your view     controller where you want to use.

If you want to Share your feeds In your Facebook through on your button click event Then refer the below code .

//When sharing Only String on Facebook
  [[ShareFile sharedSinglton] Fbsharing:@"Rathod's Demo"];

If Sharing  String and URL  on FaceBook

// When sharing String, URL on Facebook
[[ShareFile sharedSinglton] Fbsharing:@"Rathod's Demo" :[NSURLURLWithString:@"http://aniruddhsinhiostutorial.blogspot.in/"]];

If Sharing  String , URL and Image  on FaceBook

// When sharing String, URL and Image on Facebook
[[ShareFile sharedSinglton] Fbsharing:@"Rathod's Demo" :[NSURLURLWithString:@"http://aniruddhsinhiostutorial.blogspot.in/"] :[UIImage imageNamed:@"AniruddhSinh.png"]];

If you want to Share your feeds In your Twitter through on your button click event Then refer the below code .

//When sharing Only String on Twitter
[[ShareFile sharedSinglton] twittersharing:@"Rathod's Demo"];
If Sharing  String and URL  on Twitter

//When sharing String, URL on Twitter
[[ShareFile sharedSinglton]twittersharing:@"Rathod's Demo":[NSURLURLWithString:@"http://aniruddhsinhiostutorial.blogspot.in/"] :[UIImage imageNamed:@"AniruddhSinh.png"]];

If Sharing  String , URL and Image  on Twitter

// When sharing String, URL and Image on Twitter
[[ShareFile sharedSinglton] twittersharing:@"Rathod's Demo" :[NSURLURLWithString:@"http://aniruddhsinhiostutorial.blogspot.in/"] :[UIImage imageNamed:@"AniruddhSinh.png"]];

here you can share your feeds in your Facebook and Twitter with the help of above code . so enjoy every movement of programing. Thank you.

Note :- You Must Configure you Facebook and Twitter Account in your Device.

Collection View

Collection View


1 )  First set CollectionView in Your Storyboard ...


2 )  Write Coding in ViewController.h File...


@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegate>
{
    __weak IBOutlet UICollectionView *objCollectionView;
    
}

@end


3 )  Write Coding in ViewController.m File...



@implementation ViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [objCollectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"Cell"];
    [objCollectionView setAllowsMultipleSelection:YES];
 
}

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

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 60;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionReusableView *reusableview = nil;
    
    return reusableview;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(72, 72);
}
// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier=@"Cell";
    
    UICollectionViewCell *objCollection=(UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    
    objCollection.backgroundView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:@"%d.png", [indexPath row] % 16]]];
    
    return objCollection;
    
}
- (void) selectCellForCollectionView:(UICollectionView *)collection atIndexPath:(NSIndexPath *)indexPath
{
    [collection selectItemAtIndexPath:indexPath animated:YES scrollPosition:UICollectionViewScrollPositionNone];
    [self collectionView:collection didSelectItemAtIndexPath:indexPath];
}

- (void) deselectCellForCollectionView:(UICollectionView *)collection atIndexPath:(NSIndexPath *)indexPath
{
    [collection deselectItemAtIndexPath:indexPath animated:YES];
    [self collectionView:collection didDeselectItemAtIndexPath:indexPath];
}

@end

XML Parsar ( GdataXml parser )

XML Parsar

Xml Example :

Hi Friends !!!  Here I am Trying My Best To explain how Use  Xml  In IOS. So,I think its may be very helpful to you, Because here I am Trying so simple & easy  language and method so that everyone can understand it very quickly.
Here xml Example using the GdataXml parser..

1. First put the xml folder in your new project ...(that given below) in this Folder include the AsiHttp ,GdataXml ,Rss ,Singleton Folders.

Xml folder

2. xml folder contain all the non ARC file so set the flag (-fno-objc-arc ) in compile sources.
     (go to Build Phases --> compile sources ---> set flag to -fno-objc-arc)

3. add following  framework in your project
   -security.framework
   -systemConfiguratin.framework
   -libz.dylib
   -MobileCoreServices.framework
   -CFNetwork.framework
   -libxml2.dylib

4. inser new  path in header searchpath.(go Build Setting -> Search path-->Header Search Paths)

/usr/include/libxml2 

and  finally build your project..(cmd +b). (if error occur than see and check again all step).
so no error occur than ...

your viewcontroller.h

//  ViewController.h
//  xml demo
//  Created by Ilesh panchal on 
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
{
    NSMutableArray *allEntries;
    NSOperationQueue *queue;
    NSMutableArray *arrData;
}
@property (nonatomic,strong) NSMutableArray *allEntries;
@property (nonatomic,strong) NSOperationQueue *queue;
@property (nonatomic,strong) NSMutableArray *arrData;
@end

and view controller .m flle put the following method..
--- Import following files

#import "ASIHTTPRequest.h"
#import "GDataXMLNode.h"
#import "GDataXMLElement-Extras.h"
#import "NSDate+InternetDateTime.h"
#import "NSArray+Extras.h"
#import "Singleton.h"
In viewDidLoad Method put this file in that..
    arrData=[[NSMutableArray alloc] init];
    self.allEntries = [NSMutableArray array];
    self.queue = [[NSOperationQueue alloc] init];
    // changge your url in this..
    NSURL *url = [NSURL    URLWithString:@"http://www.sandesh.com/cms/xml/Ahmedabad%20District.xml"];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [_queue addOperation:request];
copy the following method ..
- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries {
    if ([rootElement.name compare:@"rss"] == NSOrderedSame) {
        [self parseRss:rootElement entries:entries];
    } else {
        NSLog(@"Unsupported root element: %@", rootElement.name);
    }
}
- (void)requestFinished:(ASIHTTPRequest *)request {
  [_queue addOperationWithBlock:^{
        NSError *error;
        GDataXMLDocument *doc = [[GDataXMLDocument alloc]initWithData:[request responseData] options:0 error:&error];
        if (doc == nil) {
            NSLog(@"Failed to parse %@", request.url);
        } else {
            NSMutableArray *entries = [NSMutableArray array];
            [self parseFeed:doc.rootElement entries:entries];
            // [[NSOperationQueue mainQueue] addOperationWithBlock:^{ }];
        }
    }];
}
- (void)requestFailed:(ASIHTTPRequest *)request {
    NSError *error = [request error];
    NSLog(@"Error: %@", error);
   }
and finally add the following method and modify your tag is different ..
- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries
{   
     //here my first tag in the rss fied ...
    NSArray *channels = [rootElement elementsForName:@"channel"];
       // NSLog(@"%@",channels);
    for (GDataXMLElement *channel in channels)
    {   
        NSArray *items = [channel elementsForName:@"item"];
        //NSLog(@"%@",items);
        for (GDataXMLElement *item in items) 
    {
     NSString *articleTitle = [item valueForChild:@"title"];
     NSLog(@"%@",articleTitle);
 //  NSString *strDes = [item valueForChild:@"description"];
 //  NSString *strLink =[item valueForChild:@"link"];
//  NSString *articleDateString = [item valueForChild:@"pubDate"];

   NSString *strcity = [(GDataXMLElement *) [locations attributeForName:@"city"] stringValue];      

 // if data is in Custom  tag then Get data using This Coding :-[ <yweather:location city="Rudersdorf" region="OO" country="Austria"/> ]


        }

    }
}

Calculator


1 )  First Of All Set Your StoryBoard Like This ...



2 ) Then Set Button Tag From The Property Window .... 


         Set    1   to   9   tag as it is Number 
         Set    0   to  10
         Set   +   to   11
         Set   -   to    12
         Set   *   to    13
         Set   /    to    14
         Set   %   to   15
         Set   =   to    16
         Set   C   to   17


3)   Write Code In ViewController.h File Like This ...



@interface ViewController : UIViewController<UITextFieldDelegate>
{
    int a;
    int b;
    int c;
}

@property (strong, nonatomic) IBOutlet UITextField *textfield;
- (BOOL)textFieldShouldReturn:(UITextField *)textField;   
@end


4)   Write Code In ViewController.m File Like This ...


@implementation ViewController
@synthesize textfield;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
     // Dispose of any resources that can be recreated.
}
- (IBAction)genralmethod:(UIButton *)sender
{
    textfield.text=[textfield.text stringByAppendingString:sender.titleLabel.text];
}
- (IBAction)genralopmethod:(UIButton *)sender
{
     a=[textfield.text intValue];
    if (sender.tag==11)
    {
        c = sender.tag;
        textfield.text = @"";
      
    }
    else if (sender.tag==12)
    {
        c = sender.tag;
        textfield.text = @"";
        
    }
    else if (sender.tag==13)
    {
        c = sender.tag;
        textfield.text = @"";
    }
    else if (sender.tag==14)
    {
        c = sender.tag;
        textfield.text = @"";
    }
    else if (sender.tag==15)
    {
        c = sender.tag;
        textfield.text = @"";
    }
    else if (sender.tag == 17)
     {
        textfield.text = @"";
    }
   
}

- (IBAction)eq:(UIButton *)sender
{
    if (sender.tag==16)
   {
       switch (c) {
           case 11:
               b = a + [textfield.text intValue];
               textfield.text=[NSString stringWithFormat:@"%d",b];
               break;
               case 12:
               b = a - [textfield.text intValue];
               textfield.text=[NSString stringWithFormat:@"%d",b];
               break;
               case 13:
               b = a * [textfield.text intValue];
               textfield.text=[NSString stringWithFormat:@"%d",b];
               break;
               case 14:
               b = a / [textfield.text intValue];
               textfield.text=[NSString stringWithFormat:@"%d",b];
               break;
               case 15:
               b = a % [textfield.text intValue];
               textfield.text=[NSString stringWithFormat:@"%d",b];
               break;
               
           default:
               break;
       }
       
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{

    [textfield resignFirstResponder];
    return YES;
}

@end

Wednesday, 28 January 2015

Json Parser

Json parsar

Here json Example using the NXJson parser..

There are Two Method To Do This ..... It Is Given Below :

Method ( 1 ) :-

-: First Call Method In Viewdidload and Write This Code In Method :-



NSHTTPURLResponse *responce = nil;
    
    NSString *urlstring = [NSString stringWithFormat:@"http://phobos.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/toppaidapplications/limit=20/json"];
    
    NSURL *urldata = [NSURL URLWithString:[urlstring stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLRequest *urlrequest = [[NSURLRequest alloc]initWithURL:urldata];
    
    NSData *mydata = [NSURLConnection sendSynchronousRequest:urlrequest returningResponse:&responce error:nil];
    
    NSMutableDictionary *maindic = [NSJSONSerialization JSONObjectWithData:mydata options:NSJSONReadingMutableContainers error:nil];

Then Write Coding To Fetch Your Data Depend Your Need .... Example Is Given Below

NSMutableDictionary *feeddic = [maindic objectForKey:@"feed"];
    
    
    NSMutableArray *mainarr = [feeddic objectForKey:@"entry"];
    
    for (int i = 0; i < mainarr.count; i++)
    {
        
        Container *data = [[Container alloc] init];
        
        NSMutableDictionary *subdic = [mainarr objectAtIndex:i];
        
        NSMutableDictionary *secnamedic = [subdic objectForKey:@"im:name"];
        
        NSString *stringsecname = [secnamedic objectForKey:@"label"];
        
        data.strsecname = stringsecname;
        
        NSMutableArray *imgarr = [subdic objectForKey:@"im:image"];
        
        for (int j = 0; j < imgarr.count; j++)
        {
            NSMutableDictionary *secsubdic = [imgarr objectAtIndex:0];
            
            NSString *stringimg = [secsubdic objectForKey:@"label"];

            data.strimg=stringimg;
          
        }
      
        [arrobj addObject:data];

    }
  
    [tblobj reloadData];


Method ( 2) :-


1. First put the json folder in your new project Or Exiting project ...(that given below) in this Folder  include the AsiHttp,json,singlton,Staticclass,Singleton folder .

  Click here for Download Jason file :-   A

this file must import in your bundel.....


Json Folder contain This class files


2. json folder contain all the non ARC file so set the flag (-fno-objc-arc ) in compile sources.
     (go to Build Phases --> compile sources ---> set flag to -fno-objc-arc)

3. add following  framework in your project

    1  -  security.framework
    2  -  systemConfiguratin.framework
    3 -   libz.dylib
    4  -  MobileCoreServices.framework
    5  -  CFNetwork.framework
    6  -  libxml2.dylib

4. inser new  path in header searchpath.

(go Build Setting -> Search path-->Header Search Paths)


/usr/include/libxml2 

and  finally build your project..(cmd +b). (if error occur than see and check again all step).
 NOTE :- if you get some syntax error then double click on them and fix -it .
so no error occur than ...
Then start you project to working json file..

First of all Import These Three files.

#import "Singleton.h"
#import "HttpQueue.h"
#import "NXJsonParser.h"


Then After In ViewDidLoad method register a notification.

-(void)viewDidLoad
{ 
 [super viewDidLoad];
  

[[NSNotificationCenter defaultCenter] removeObserver:self name:@"1" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getAllAPIDataCompletion:) name:@"1" object:nil];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"-1" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getAllAPIDataFail:) name:@"-1" object:nil];


}

send request using httpQueue class and get response to given Method. 


-(void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:animated];
    
    NSString *myreqstr=[NSString stringWithFormat:@"http://phobos.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/toppaidapplications/limit=10/json"]; // using The Raywendrlich json api for demo
    
    [[HttpQueue sharedSingleton] getItems:myreqstr :1];
    

}

When request is successful get all data This method.


-(void ) getAllAPIDataCompletion : (NSNotification *)notification {
    
    NSDictionary *dict = [notification userInfo];
    
    ASIHTTPRequest *res = [dict objectForKey:@"index"];
    
    NXJsonParser * parser = [[NXJsonParser alloc] initWithData:[res responseData]];
    
    id result = [parser parse:nil ignoreNulls:NO];
    
    NSDictionary *maindic = (NSDictionary *)result;
    NSDictionary *feeddic = [maindic objectForKey:@"feed"];
    NSArray *entryarr = [feeddic objectForKey:@"entry"];
    
    
    for (int i=0; i<entryarr.count; i++)
    {
        Container *contain = [[Container alloc] init];
        
        
        NSDictionary *subdic = [entryarr objectAtIndex:i];
        NSDictionary *namedic = [subdic objectForKey:@"im:name"];
        NSString *strname = [namedic objectForKey:@"label"];
        
        contain.strname = strname;
        
        NSArray *imgarr = [subdic objectForKey:@"im:image"];
        for (int j=0; j<imgarr.count; j++)
        {
            NSDictionary *imgdic = [imgarr objectAtIndex:j];
            NSString *strimg = [imgdic objectForKey:@"label"];
            
            contain.strimg = strimg;
            
        }
        
        [myarr addObject:contain];
    }

    [tblobj reloadData];
}





And  Fail the reason of wrong url and network fail then call this method ..


-(void ) getAllAPIDataFail : (NSNotification *)notification {
    
    NSDictionary *dict = [notification userInfo];
    
    ASIHTTPRequest *res = [dict objectForKey:@"index"];
    
    NXJsonParser * parser = [[NXJsonParser alloc] initWithData:[res responseData]];
    
    id result = [parser parse:nil ignoreNulls:NO];
    
    NSLog(@"result=%@",result);
    

}

Run This project and get following out put if you get error please see above the step again .
Output in Log.



Well, This time to Get the useful data in this all Data . In this result first `{} `contain (NSDictionary ) and `( )`Or `[ ]`contain  (NSArray). if you want to get Activity`s value from the loans Then you have to implement This Step by Step.
Here in the Data `{` indicate Dictionary so we hold This Dictionary in NSDictionary .


 For Api :- 

http://phobos.apple.com/WebObjects/MZStoreServices.woa/ws/RSS/toppaidapplications/limit=10/json


    NSDictionary *maindic = (NSDictionary *)result;


    NSDictionary *feeddic = [maindic objectForKey:@"feed"];

    NSArray *entryarr = [feeddic objectForKey:@"entry"];
    
    
    for (int i=0; i<entryarr.count; i++)

   {

    Container *contain = [[Container alloc] init];     // create object of Nsobject(Container)
        
        
        NSDictionary *subdic = [entryarr objectAtIndex:i]; 

        NSDictionary *namedic = [subdic objectForKey:@"im:name"];

        NSString *strname = [namedic objectForKey:@"label"];
        
        contain.strname = strname;                              // fetch data in container
        
        NSArray *imgarr = [subdic objectForKey:@"im:image"];

        for (int j=0; j<imgarr.count; j++)

        {

            NSDictionary *imgdic = [imgarr objectAtIndex:j];

            NSString *strimg = [imgdic objectForKey:@"label"];
            
            contain.strimg = strimg;                                    // fetch data in container
            
        }
        
        [myarr addObject:contain];
    }
    
    
    [tblobj  reloadData];



Note :- In the Method of Table view new Object is needed to Show the Data.

ex :-


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

    Container *data = [myarr objectAtIndex:indexPath.row];
    
    MyCell *cell = [tblobj dequeueReusableCellWithIdentifier:@"cell"];
    
    cell.lbl.text = data.strname;

    cell.imageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:                                                     [NSURL URLWithString:data.strimg]]];
    
    return cell;


}


I think Its May be Very Helpful to You.Thanks!!