Displya Data in tableview (WEBSERVICE)

NewsEventsCellTableViewCell.h

#import <UIKit/UIKit.h>

@interface NewsEventsCellTableViewCell : UITableViewCell{

    IBOutlet UIImageView *imgLblBg;

    IBOutlet UILabel *lblDate;

}

@property (nonatomic , retain) IBOutlet UIImageView *imgLblBg;

@property (nonatomic , retain) IBOutlet UILabel *lblDate;

@end

NewsEventsCellTableViewCell.m

#import “NewsEventsCellTableViewCell.h”

@implementation NewsEventsCellTableViewCell

@synthesize imgLblBg,lblDate;

– (void)awakeFromNib {

    // Initialization code

}

– (void)setSelected:(BOOL)selected animated:(BOOL)animated {

    [super setSelected:selected animated:animated];

    // Configure the view for the selected state

}

@end

====================================

===================================

NewsEventsVC.h

#import <UIKit/UIKit.h>

#import “NewsDetailsVC.h”

@interface NewsEventsVC : UIViewController<UITableViewDataSource,UITableViewDelegate>

{

    IBOutlet UILabel *lblHeader;

    IBOutlet UIImageView *imgTopView;

      NewsDetailsVC *objNewsDetailsVC;

}

@property (weak, nonatomic) IBOutlet UITableView *tableVIew;

@property (nonatomic, strong) NSMutableArray *tableViewDataSources;

@end

NewsEventsVC.m

#import “NewsEventsVC.h”

#import “NewsEventsCellTableViewCell.h”

#import “UtilityLibrary.h”

#import “Constant.h”

#import “MBProgressHUD.h”

@interface NewsEventsVC ()

@end

@implementation NewsEventsVC

– (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view.

    imgTopView.backgroundColor = [UIColor colorWithRed:188.0/255.0 green:224.0/255.0 blue:72.0/225.0 alpha:1.0];

    self.tableViewDataSources = [[NSMutableArray alloc] init];

    [lblHeader setFont:[UIFont fontWithName:txtHeaderFontName size:30.0f]];

    [self getNewsEventsList];

}

– (IBAction)btnBack:(id)sender{

    

    [self.navigationController popViewControllerAnimated:YES];

    

}

– (IBAction)btnReference:(id)sender{

    

    [self getNewsEventsList];

    [self.tableVIew reloadData];

}

– (IBAction)mthHome:(id)sender{

    

//    [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:self.navigationController.viewControllers.count – 4] animated:YES];

    

    [self.navigationController popViewControllerAnimated:YES];

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

#pragma mark – UITableView DataSource and Delegate Methods –

– (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView

{

    return 1;

}

– (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    return self.tableViewDataSources.count;

}

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

{

    NewsEventsCellTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@”NewsEventsCellTableViewCell”];

    if (cell == nil) {

        NSArray *array = [[NSBundle mainBundle] loadNibNamed:@”NewsEventsCellTableViewCell” owner:self options:nil];

        cell = [array objectAtIndex:0];

    }

    

    NSLog(@”tableViewDataSources==>%@”,self.tableViewDataSources);

    cell.imgLblBg.backgroundColor = [UIColor colorWithRed:188.0/255.0 green:224.0/255.0 blue:72.0/225.0 alpha:1.0];

    

    cell.selectionStyle = UITableViewCellSelectionStyleNone;

    UILabel *lblData = (UILabel *) [cell viewWithTag:1];

    UILabel *lblDate = (UILabel *) [cell viewWithTag:2];

    

    lblData.text =  [[self.tableViewDataSources objectAtIndex:indexPath.row] objectForKey:@”title”];

    lblDate.text = [[self.tableViewDataSources objectAtIndex:indexPath.row] objectForKey:@”eventDate”];

    

    [lblData setFont:[UIFont fontWithName:txtHeaderFontName size:25.0f]];

    [lblDate setFont:[UIFont fontWithName:txtHeaderFontName size:10.0f]];

    lblDate.transform = CGAffineTransformMakeRotation(-M_PI / 2);

    

    return cell;

}

– (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{

    //J.D…..

    objNewsDetailsVC=[self.storyboard instantiateViewControllerWithIdentifier:@”NewsDetailsVC”];

    

    NSString *strDetails = [[self.tableViewDataSources objectAtIndex:indexPath.row] objectForKey:@”description”];

    objNewsDetailsVC.strDescription = strDetails;

    NSString *strTitleHeader = [[self.tableViewDataSources objectAtIndex:indexPath.row] objectForKey:@”title”];

    objNewsDetailsVC.strTitle = strTitleHeader;

    

    [self.navigationController pushViewController:objNewsDetailsVC animated:YES];

    

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath

{

    return 92;

}

-(void)getNewsEventsList

{

    //J.D…..

    //ADD…..

    @try {

        

        UtilityLibrary *util = [[UtilityLibrary alloc] init];

        NSArray *arrayKeys = [NSArray arrayWithObjects:@”apiKey”, nil];

        NSArray *arrayValues = [NSArray arrayWithObjects:kAPI_KEY, nil];

        NSDictionary *dicParameters = [NSDictionary dictionaryWithObjects:arrayValues forKeys:arrayKeys];

        

        [MBProgressHUD showHUDAddedTo:self.view animated:YES];

        

        [util postDataWithURL:[NSString stringWithFormat:@”%@%@”,kHeaderURL,ViewEvent] andParameters:dicParameters success:^(id responce) {

            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

            if ([[responce objectForKey:@”errorcode”] integerValue] == 1) {

                

                NSLog(@”RESPONCE%@==>”,responce);

                

                [self.tableViewDataSources removeAllObjects];

                [self.tableViewDataSources addObjectsFromArray:[responce objectForKey:@”data”]];

                [self.tableVIew reloadData];

            }

        } failure:^(NSError *error) {

            [MBProgressHUD hideAllHUDsForView:self.view animated:YES];

        }];

    }

       @catch (NSException *exception) {

        NSLog(@”%@”,exception.description);

    }

   }

@end

=========================================================

UtilityLibrary.h

==========================================================

//

//  UtilityLibrary.h

//  TestLibrary

//

//  Created by Bipul Dev on 12/4/13.

//

#import <Foundation/Foundation.h>

#import “AFHTTPRequestOperationManager.h”

#import “AFURLSessionManager.h”

#import <Social/Social.h>

#import <Accounts/Accounts.h>

// define the protocol for the delegate

@protocol UitilitiesLibraryDelegate

// define protocol functions that can be used in any class using this delegate

//use when fetchingDatafromURL & fetchingDataOnlyfromURL function is used

-(void)Responce:(id)collection withRequestTag:(NSString *)tagStr andInfodictionary:(NSDictionary *)dict;

-(void)errorOccured:(NSError *)error;

@end

@interface UtilityLibrary : NSObject

{

    AFHTTPRequestOperationManager *managerObject;

}

// cancels all the operation of afnetworking.

-(void)cancelAllOperations;

-(void)getDataFromURL:(NSString *)str withParameters:(NSDictionary *)parameters andKey:(NSString *)key success:(void(^)(id responce))successResponce failure:(void(^)(NSError *error))failureResponce;

-(void)postDataWithURL:(NSString *)str andParameters:(NSDictionary *)parameters success:(void(^)(id responce))successResponce failure:(void(^)(NSError *error))failureResponce;

-(void)downloadWithURL:(NSString *)str saveToPath:(NSString *)path success:(void(^)(id responce))successResponce failure:(void(^)(NSError *error))failureResponce;

-(void)uploadWithURL:(NSString *)str andfilePath:(NSString *)path andName:(NSString *)controlName andParameters:(NSDictionary *)parameters success:(void(^)(id responce))successResponce failure:(void(^)(NSError *error))failureResponce;

-(void)uploadMultipleFileWithURL:(NSString *)str andfilePath:(NSMutableArray *)pathArray andVideoPath:(NSString *)videoPath andName:(NSString *)controlName andParameters:(NSDictionary *)parameters success:(void(^)(id responce))successResponce failure:(void(^)(NSError *error))failureResponce;

@property (nonatomic,assign) id delegate;

//Showing Simple Alert

+(void)showAlertWithTitle:(NSString *)title message:(NSString *)messageString andButtonTitle:(NSString *)btnTitle;

//Posting On Facebook

+(void)sendFacebookPost:(NSString *)title withImage:(UIImage *)path addComposerToViewController:(UIViewController *)controller;

//Posting On Twitter

+(void)sendTwiterPost:(NSString *)title withImage:(UIImage *)path addComposerToViewController:(UIViewController *)controller;

-(void)requestTwitterPermission:(NSString *)appKeyId withUserInfo:(BOOL)wantUserInfo ProfilePic:(BOOL)wantProfilePic success:(void(^)(id responce, NSString *tagstr))successResponce failure:(void(^)(NSError *error))failureResponce;

@end

============================================================

UtilityLibrary.m

============================================================

//

//  UtilityLibrary.m

//  TestLibrary

//

//  Created by Bipul Dev on 12/4/13.

//

#import “UtilityLibrary.h”

#import “AppDelegate.h”

@interface UtilityLibrary()

{

    AppDelegate *appDel;

}

@property (nonatomic,copy) void(^getProducts)(NSArray * productIdentifiers);

@property (nonatomic,copy) void(^getData)(NSData * imageData, NSString * tag);

@property (nonatomic,retain) NSArray *arrayAvailableProducts;

@end

@implementation UtilityLibrary

@synthesize delegate,arrayAvailableProducts;

-(id)init

{

    if (!self)

    {

        self = [super init];

    }

    managerObject = [AFHTTPRequestOperationManager manager];

    appDel = (AppDelegate *)[ [UIApplication sharedApplication] delegate];

    return self;

}

-(void)cancelAllOperations

{

    [managerObject.operationQueue cancelAllOperations];

}

#pragma mark –

#pragma mark GET

-(void)getDataFromURL:(NSString *)str withParameters:(NSDictionary *)parameters andKey:(NSString *)key success:(void(^)(id responce))successResponce failure:(void(^)(NSError *error))failureResponce

{

    managerObject.responseSerializer = [AFHTTPResponseSerializer serializer];

    if (parameters!=nil)

    {

        NSData *data  = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:nil];

        NSString *jsonString = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding];

        NSString *requestString;

        if (key!=nil)

        {

            requestString = [NSString stringWithFormat:@”%@=%@”,key,jsonString, nil];

        }

        else

        {

            requestString = [NSString stringWithFormat:@”%@”,jsonString, nil];

        }

        NSString *urlstr = [NSString stringWithFormat:@”%@%@”,str,requestString];

        urlstr = [urlstr stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

        

        [managerObject GET:urlstr parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)

         {

             NSData *responce = responseObject;

             id json = [NSJSONSerialization JSONObjectWithData:responce options:NSJSONReadingAllowFragments error:nil];

             successResponce(json);

             

         }failure:^(AFHTTPRequestOperation *operation, NSError *error)

         {

             failureResponce(error);

         }];

        }

    else

    {

        [managerObject GET:str parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)

         {

             NSData *responce = responseObject;

//             id json = [NSJSONSerialization JSONObjectWithData:responce options:NSJSONReadingAllowFragments error:nil];

             successResponce(responce);

                      }failure:^(AFHTTPRequestOperation *operation, NSError *error)

         {

             failureResponce(error);

         }];

    }

    }

#pragma mark –

#pragma mark POST

-(void)postDataWithURL:(NSString *)str andParameters:(NSDictionary *)parameters success:(void(^)(id responce))successResponce failure:(void(^)(NSError *error))failureResponce

{

    managerObject.responseSerializer = [AFHTTPResponseSerializer serializer];

    [managerObject POST:str parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)

     {

         NSData *responce = responseObject;

         id json = [NSJSONSerialization JSONObjectWithData:responce options:NSJSONReadingAllowFragments error:nil];

         successResponce(json);

    } failure:^(AFHTTPRequestOperation *operation, NSError *error)

    {

        failureResponce(error);

    }];

}

//MULTIPLE IMAGES…..

– (void)uploadMultipleFileWithURL:(NSString *)BaseURLString

                      andfilePath:(NSMutableArray *)pathArray

                    andParameters:(id)parameters

                    withBasicAuth:(NSString *)basicAuth

                 withXAuthHeaders:(NSString *)XAuth

                          success:(void(^)(AFHTTPRequestOperation *operation, id responce))successResponce

                          failure:(void(^)(AFHTTPRequestOperation *operation, NSError *error))failureResponce{

    

        managerObject.responseSerializer = [AFHTTPResponseSerializer serializer];

    

    NSLog(@”BaseURLString==%@”,BaseURLString);

    

    NSLog(@”parameters%@”,parameters);

      // Show Network ActivityIndicator

// POST Method to send parameterr

        [managerObject POSTUploadFile:BaseURLString basicAuth:basicAuth XAuth:XAuth parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {

        

        if ([pathArray isKindOfClass:[NSArray class]]) {

               NSArray *arr = (NSArray *)pathArray;

            for (int i=0; i<[arr count]; i++) {

                

                NSDictionary *dic = arr[i];

                

                NSString *strFileName = @””;

                NSData  *imgData = [NSData dataWithContentsOfFile:strFileName];

                

//                [formData appendPartWithFileData:imgData

//                 

//                                            name:[NSString stringWithFormat:@”%@”,dic[ControlName]]

//                 

//                                        fileName:[NSString stringWithFormat:@”%@”,strFileName]

//                 

//                                        mimeType:@”image/jpeg”];

                

            }

            

        }

        

        

        

    } success:^(AFHTTPRequestOperation *operation, id responseObject) {

        

        NSData *responce = responseObject;

        

        

        

        id json = [NSJSONSerialization JSONObjectWithData:responce options:NSJSONReadingAllowFragments error:nil];

        

        NSLog(@”RESPONSE STRING FOR IMAGES = %@”,[[NSString alloc]initWithData:responce encoding:NSStringEncodingConversionAllowLossy]);

        

        

        successResponce(operation, json);

        

        

        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {

        

        failureResponce(operation, error);

        

        

        

    } ];

    

    

    

}

-(void)uploadMultipleFileWithURL:(NSString *)str andfilePath:(NSMutableArray *)pathArray andVideoPath:(NSString *)videoPath andName:(NSString *)controlName andParameters:(NSDictionary *)parameters success:(void(^)(id responce))successResponce failure:(void(^)(NSError *error))failureResponce

{

    

    managerObject.responseSerializer = [AFHTTPResponseSerializer serializer];

    [managerObject POST:str parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)

     

     {

         

         if ([videoPath length] != 0) {

             

             NSURL *fileVideoPath = [NSURL fileURLWithPath:[NSString stringWithFormat:@”%@”,videoPath]];

             

             [formData appendPartWithFileURL:fileVideoPath name:controlName error:nil];

             

         }

         

         if ([pathArray isKindOfClass:[NSArray class]]) {

             

             NSArray *arr = (NSArray *)pathArray;

             

             

             

             for (int i=0; i<[arr count]; i++) {

                 

                 

                 

                 NSData  *imgData = [NSData dataWithContentsOfFile:[arr objectAtIndex:i]];

                 

                 [formData appendPartWithFileData:imgData

                  

                                             name:[NSString stringWithFormat:@”%@”,controlName]

                  

                                         fileName:[NSString stringWithFormat:@”%d.png”,i]

                  

                                         mimeType:@”image/png”];

             }

             

         }

         

     } success:^(AFHTTPRequestOperation *operation, id responseObject)

     

     {

         //

         NSData *responce = responseObject;

         

         id json = [NSJSONSerialization JSONObjectWithData:responce options:NSJSONReadingAllowFragments error:nil];

         

         NSLog(@”RESPONSE STRING FOR IMAGES = %@”,[[NSString alloc]initWithData:responce encoding:NSStringEncodingConversionAllowLossy]);

         successResponce(json);

         

     } failure:^(AFHTTPRequestOperation *operation, NSError *error)

     

     {

         

         if (operation.response.statusCode == 403) {

             

             NSString *kshowlogoutMessage = @”kshowlogoutMessage”;

             

             [[NSNotificationCenter defaultCenter] postNotificationName:kshowlogoutMessage object:nil];

             

         }

         

         failureResponce(error);

         

     }];

    

}

#pragma mark –

#pragma mark Download

-(void)downloadWithURL:(NSString *)str saveToPath:(NSString *)path success:(void(^)(id responce))successResponce failure:(void(^)(NSError *error))failureResponce

{

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

    

    NSURL *URL = [NSURL URLWithString:str];

    NSURLRequest *request = [NSURLRequest requestWithURL:URL];

    

    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response)

    {

        if (path != nil)

        {

            return [NSURL URLWithString:path];

        }

        else

        {

            NSURL *documentsDirectoryPath = [NSURL fileURLWithPath:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]];

            return [documentsDirectoryPath URLByAppendingPathComponent:[targetPath lastPathComponent]];

        }

        

    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error)

    {

        successResponce(filePath);

    }];

    [downloadTask resume];

}

#pragma mark –

#pragma mark UPLOAD

-(void)uploadWithURL:(NSString *)str andfilePath:(NSString *)path success:(void(^)(id responce))successResponce failure:(void(^)(NSError *error))failureResponce

{

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

    

    NSURL *URL = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];

    NSURLRequest *request = [NSURLRequest requestWithURL:URL];

    

    NSURL *filePath = [NSURL fileURLWithPath:path];

    NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {

        if (error)

        {

            failureResponce(error);

        }

        else

        {

            successResponce(responseObject);

        }

    }];

    [uploadTask resume];

}

#pragma mark –

#pragma mark UPLOAD With Parameters

//@”dealImage”

-(void)uploadWithURL:(NSString *)str andfilePath:(NSString *)path andName:(NSString *)controlName andParameters:(NSDictionary *)parameters success:(void(^)(id responce))successResponce failure:(void(^)(NSError *error))failureResponce

{

    managerObject.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSURL *filePath = [NSURL fileURLWithPath:[NSString stringWithFormat:@”%@”,path]];

    [managerObject POST:str parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)

     {

        [formData appendPartWithFileURL:filePath name:controlName error:nil];

    } success:^(AFHTTPRequestOperation *operation, id responseObject)

    {

        NSData *responce = responseObject;

       

        id json = [NSJSONSerialization JSONObjectWithData:responce options:NSJSONReadingAllowFragments error:nil];

        successResponce(json);

        

    } failure:^(AFHTTPRequestOperation *operation, NSError *error)

    {

        failureResponce(error);

    }];

    

    

}

#pragma mark Alert showing

+(void)showAlertWithTitle:(NSString *)title message:(NSString *)messageString andButtonTitle:(NSString *)btnTitle

{

    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:messageString delegate:self cancelButtonTitle:btnTitle otherButtonTitles:nil, nil];

    [alert show];

    

}

//++++++++++++++++++++FACEBOOK POSTING++++++++++++++++++++++++++++++

//++++++++++++++++++++++++++++++++++++++++++++++++++

//++++++++++++++++++++++++++++++++++++++++

#pragma mark –

#pragma mark posting on facebook

+(void)sendFacebookPost:(NSString *)title withImage:(UIImage *)path addComposerToViewController:(UIViewController *)controller

{

    SLComposeViewController *mySLComposerSheet;

    {

        mySLComposerSheet = [[SLComposeViewController alloc] init]; //initiate the Social Controller

        mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook]; //Tell him with what social plattform to use it, e.g. facebook or twitter

        [mySLComposerSheet setInitialText:title]; //the message you want to post

        if (path)

        {

            [mySLComposerSheet addImage:path]; //an image you could post

        }

        

        //for more instance methodes, go here:https://developer.apple.com/library/ios/#documentation/NetworkingInternet/Reference/SLComposeViewController_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40012205

        [controller presentViewController:mySLComposerSheet animated:YES completion:nil];

    }

    [mySLComposerSheet setCompletionHandler:^(SLComposeViewControllerResult result)

     {

         

         switch (result)

         {

             case SLComposeViewControllerResultCancelled:

                 //output = @”Action Cancelled”;

                 break;

             case SLComposeViewControllerResultDone:

                break;

             default:

                 break;

         } //check if everythink worked properly. Give out a message on the state.

//         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Facebook” message:output delegate:nil cancelButtonTitle:@”Ok” otherButtonTitles:nil];

//         [alert show];

     }];

}

//++++++++++++++++++++Twitter POSTING++++++++++++++++++++++++++++++

//++++++++++++++++++++++++++++++++++++++++++++++++++

//++++++++++++++++++++++++++++++++++++++++

#pragma mark –

#pragma mark tweeting on twitter

+(void)sendTwiterPost:(NSString *)title withImage:(UIImage *)path addComposerToViewController:(UIViewController *)controller

{

    SLComposeViewController *mySLComposerSheet;

    {

        mySLComposerSheet = [[SLComposeViewController alloc] init]; //initiate the Social Controller

        mySLComposerSheet = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter]; //Tell him with what social plattform to use it, e.g. facebook or twitter

        [mySLComposerSheet setInitialText:title]; //the message you want to post

        if (path)

        {

            [mySLComposerSheet addImage:path]; //an image you could post

        }

        

        //for more instance methodes, go here:https://developer.apple.com/library/ios/#documentation/NetworkingInternet/Reference/SLComposeViewController_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40012205

        [controller presentViewController:mySLComposerSheet animated:YES completion:nil];

    }

    [mySLComposerSheet setCompletionHandler:^(SLComposeViewControllerResult result)

     {

         switch (result)

         {

             case SLComposeViewControllerResultCancelled:

                 //output = @”Action Cancelled”;

                 break;

             case SLComposeViewControllerResultDone:

                 break;

             default:

                 break;

         } //check if everythink worked properly. Give out a message on the state.

//         UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@”Twitter” message:output delegate:nil cancelButtonTitle:@”Ok” otherButtonTitles:nil];

//         [alert show];

     }];

    

}

//https://graph.facebook.com/244587955553836/likes

-(void)requestTwitterPermission:(NSString *)appKeyId withUserInfo:(BOOL)wantUserInfo ProfilePic:(BOOL)wantProfilePic success:(void(^)(id responce, NSString *tagstr))successResponce failure:(void(^)(NSError *error))failureResponce

{

    // Create an account store

    ACAccountStore *twitter = [[ACAccountStore alloc] init];

    

    // Create an account type

    ACAccountType *twAccountType = [twitter accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

    

    // Request Access to the twitter account

    [twitter requestAccessToAccountsWithType:twAccountType options:nil completion:^(BOOL granted, NSError *error)

     {

         if (granted)

         {

             // Create an Account

             ACAccount *twAccount = [[ACAccount alloc] initWithAccountType:twAccountType];

             NSArray *accounts = [twitter accountsWithAccountType:twAccountType];

             if ([accounts count]>0)

             {

             

             twAccount = [accounts lastObject];

             // Version 1.1 of the Twitter API only supports JSON responses.

             // Create an NSURL instance variable that points to the home_timeline end point.

             //             NSURL *twitterURL = [[NSURL alloc] initWithString:@”https://api.twitter.com/1.1/statuses/home_timeline.json“];

             NSURL *twitterURL = [[NSURL alloc] initWithString:@”https://api.twitter.com/1.1/users/show.json&#8221;];

             

             

             

             // Version 1.0 of the Twiter API supports XML responses.

             // Use this URL if you want to see an XML response.

             //NSURL *twitterURL2 = [[NSURL alloc] initWithString:@”http://api.twitter.com/1/statuses/home_timeline.xml“];

             

             // Create a request

             SLRequest *requestUsersTweets = [SLRequest requestForServiceType:SLServiceTypeTwitter

                                                                requestMethod:SLRequestMethodGET

                                                                          URL:twitterURL

                                                                   parameters:[NSDictionary dictionaryWithObject:twAccount.username forKey:@”screen_name”]];

             

             // Set the account to be used with the request

             [requestUsersTweets setAccount:twAccount];

             

             // Perform the request

             [requestUsersTweets performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error2)

              {

                  if (error2)

                  {

                      failureResponce(error2);

                  }

                  else

                  {

                      // The output of the request is placed in the log.

                      // The output of the request is placed in the log.

                      NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];

                      

                    successResponce(jsonResponse,@”twitter”);

                  }

                  

                  

              }];

             

            

         

             // Tidy Up

             twAccount = nil;

             accounts = nil;

             twitterURL = nil;

             requestUsersTweets = nil;

            }

             else

             {

                 UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@”Twitter Account Required” message:@”You need to setup a twitter account within the Settings app.” delegate:nil cancelButtonTitle:@”Ok.” otherButtonTitles:nil, nil];

                 [alert show];

                 alert = nil;

                // [delegate errorOccured:nil];

                 failureResponce(error);

             }

         }

         

         // If permission is not granted to use the Twitter account…

         

         else

             

         {

             UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@”Twitter Account Error” message:@”Permission was not granted to this app.” delegate:nil cancelButtonTitle:@”Ok.” otherButtonTitles:nil, nil];

             [alert show];

            alert = nil;

             failureResponce(error);

         }

     }];

    

    // Tidy up

    twitter = nil;

    twAccountType = nil;

}

@end

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s