Get Font Name

for (NSString *family in [UIFont familyNames])

    {

        NSLog(@”%@”,family);

        

        for (NSString *name in [UIFont fontNamesForFamilyName:family])

        {

                NSLog(@”%@”,name);

        }

    }

Dictionary TO ARRAY

– (void)getStationDetailsMehtod{

    

    self.webService = [[WebServices alloc] init];

    

    NSArray *arrKeys,*arrValues;

    

    if ([[NSUserDefaults standardUserDefaults] objectForKey:@”UserInfo”] != nil) {

        arrKeys = [NSArray arrayWithObjects:@”station_id”,@”user_token”, nil];;

        arrValues = [NSArray arrayWithObjects:self.stationID,[[[NSUserDefaults standardUserDefaults] objectForKey:@”UserInfo”] objectForKey:@”sessiontoken”], nil];

    }

    else

    {

        arrKeys = [NSArray arrayWithObjects:@”station_id”, nil];;

        arrValues = [NSArray arrayWithObjects:self.stationID, nil];

    }

    

    NSDictionary *dicParameter = [NSDictionary dictionaryWithObjects:arrValues forKeys:arrKeys];

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

    

    [self.webService getStationWebServicesWithParameters:dicParameter success:^(id responce) {

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

        NSLog(@”Responce DATA = %@”,dic);

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

        

        if ([[dic objectForKey:@”status”] integerValue] == 100) {

            

            NSLog(@”DIC:-%@”,dic);

            

                txtInformation.text = [[[dic objectForKey:@”message”] objectForKey:@”location”]objectForKey:@”city”];

               

                

                NSString *cityName;

                NSString *cityState;

                NSString *cityZip;

                

                cityName = [[[dic objectForKey:@”message”] objectForKey:@”location”]objectForKey:@”city”];

                cityState = [[[dic objectForKey:@”message”] objectForKey:@”location”]objectForKey:@”street”];

                cityZip = [[[dic objectForKey:@”message”] objectForKey:@”location”]objectForKey:@”zip”];

                

            [txtInformation  setText:[NSString stringWithFormat:@”%@\n%@\n%@”,cityName,cityState,cityZip]];

            

            [txtInformation setFont:[UIFont fontWithName:txtFontName size:15.0f]];

            

            for (int i = 0; i < [[[dic objectForKey:@”message”] objectForKey:@”bikes”] count]; i++) {

                

                if ([[[[[dic objectForKey:@”message”] objectForKey:@”bikes”] objectAtIndex:i] objectForKey:@”available”] integerValue] == 1) {

                    [self.arrayDataSources addObject:[[[dic objectForKey:@”message”] objectForKey:@”bikes”] objectAtIndex:i]];

                }

            }

            

        }

        

        

        [tblData reloadData];

        

    } failure:^(NSError *error) {

        NSLog(@”ERROR::: %@”,error.localizedDescription);

    }];

    

    

    

}

Open NewView

objNewAppliReg=[self.storyboard instantiateViewControllerWithIdentifier:@”NewApplicantRegistraionVC”];   app.isWebserviceViewCheck = YES;

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

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

XML PARSER……

XMLConverter.h

/**

* @class      XMLConverter XMLConverter.h “XMLConverter.h”

* @brief      XMLConverter

* @details    XMLConverter.h in XMLConverter

* @date       10/8/13

* @copyright  Copyright (c) 2013 Ruslan Soldatenko. All rights reserved.

*/

#import <Foundation/Foundation.h>

@interface XMLConverter : NSObject

/**

* The block called when XML-data convert finished

* @param[in] success YES – when XML-data convert successful, otherwise – NO.

* @param[in] dictionary Contains convert XML-data when success, otherwise – nil.

* @param[in] error Contains error of processing XML-data if exist, otherwise – nil.

*/

typedef void (^OutputBlock)(BOOL success, NSMutableDictionary *dictionary, NSError *error);

/**

*Convert XML data containing in input NSString object .

*@param[in] string Contains an NSString object with XML-data in the string format.

*@param[in] completion A block of code will be executed when the processing of XML-data is completed.

*This parameter must not be NULL.

*/

+ (void)convertXMLString:(NSString *)string completion:(OutputBlock)completion;

/**

*Convert XML data containing in input file.

*@param[in] filePath Contains an NSString object with absolute path to file with XML-data.

*@param[in] completion A block of code will be executed when the processing of XML-data is completed.

*This parameter must not be NULL.

*/

+ (void)convertXMLFile:(NSString *)filePath completion:(OutputBlock)completion;

/**

*Convert XML data containing in input NSData object.

*@param[in] data Contains NSData object with encapsulated XML contents.

*@param[in] completion A block of code will be executed when the processing of XML-data is completed.

*This parameter must not be NULL.

*/

+ (void)convertXMLData:(NSData *)data completion:(OutputBlock)completion;

/**

*Convert XML content referenced by the given URL.

*@param[in] url Contains an NSURL object specifying a URL.

*@param[in] completion A block of code will be executed when the processing of XML-data is completed.

*This parameter must not be NULL.

*/

+ (void)convertXMLURL:(NSURL *)url completion:(OutputBlock)completion;

/**

*Convert XML content from the specified stream.

*@param[in] stream Contains the specified input stream in NSInputStream object.

*@param[in] completion A block of code will be executed when the processing of XML-data is completed.

*This parameter must not be NULL.

*/

+ (void)convertXMLStream:(NSInputStream *)stream completion:(OutputBlock)completion;

@end

XMLConverter.m

/**

* @class      XMLConverter XMLConverter.m “XMLConverter.m”

* @brief      XMLConverter

* @details    XMLConverter.m in XMLConverter

* @date       10/8/13

* @copyright  Copyright (c) 2013 Ruslan Soldatenko. All rights reserved.

*/

#import “XMLConverter.h”

#define TEXT_NODE_KEY           @“#text”

#define ATTRIBUTE_PREFIX        @“-“

#define AXIS_PARENT            _axisAncestorOrSelf[_currentLevel – 1]

#define AXIS_PRECEDING_SIBLING _axisAncestorOrSelf[_currentLevel – 1][elementName]

#define AXIS_SELF              _axisAncestorOrSelf[_currentLevel]

@interface XMLConverter () <NSXMLParserDelegate>

@property (strong, nonatomic) NSMutableArray *axisAncestorOrSelf;

@property (strong, nonatomic) NSMutableString *selfText;

@property (strong, nonatomic) NSMutableDictionary *root;

@property (assign, nonatomic) NSError *error;

@property (assign, nonatomic) NSInteger currentLevel;

@end

@implementation XMLConverter

#pragma mark – Main Public Methods

+ (void)convertXMLData:(NSData *)data completion:(OutputBlock)completion

{

  ///Wrapper for -initWithData: method of NSXMLParser

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    NSXMLParser *parser = [[NSXMLParser alloc] initWithData:data];

    [[XMLConverter new] parser:parser completion:completion];

  });

}

+ (void)convertXMLURL:(NSURL *)url completion:(OutputBlock)completion

{

  ///Wrapper for -initWithContentsOfURL: method of NSXMLParser

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:url];

    [[XMLConverter new] parser:parser completion:completion];

  });

}

+ (void)convertXMLStream:(NSInputStream *)stream completion:(OutputBlock)completion

{

  ///Wrapper for -initWithStream: method of NSXMLParser

  dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

    NSXMLParser *parser = [[NSXMLParser alloc] initWithStream:stream];

    [[XMLConverter new] parser:parser completion:completion];

  });

}

#pragma mark – Additional Public Methods

+ (void)convertXMLString:(NSString *)string completion:(OutputBlock)completion

{

  //Convert input string to NSData.

  NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];

  //Use class method for NSData.

  [self convertXMLData:data completion:completion];

}

+ (void)convertXMLFile:(NSString *)filePath completion:(OutputBlock)completion

{

  //Convert input file to NSData

  NSData* data = [NSData dataWithContentsOfFile:filePath];

  //Use class method for NSData.

  [self convertXMLData:data completion:completion];

}

#pragma mark – Internal methods

– (void)parser:(NSXMLParser *)parser completion:(OutputBlock)completion

{

  ///Completion of the parser to work and run the parser.

  [parser setDelegate: self];

  //Start parsing

  BOOL success = [parser parse];

  //execute output block with results of parsing as synchronous

  dispatch_sync(dispatch_get_main_queue(), ^{

    completion(success, _root, _error);

  });

}

– (void)dealloc

{

  ///Clear out all objects

  [_axisAncestorOrSelf removeAllObjects];

  _axisAncestorOrSelf = nil;

  _selfText = nil;

  _root = nil;

}

#pragma mark – NSXMLParserDelegate Handling XML

– (void)parserDidStartDocument:(NSXMLParser *)parser

{

  ///Initialize internal objects and values

  //Set counter for current level to root element level.

  _currentLevel = 0;

  //Create storage for parsing elements.

  _axisAncestorOrSelf = [NSMutableArray new];

  //Create object for result of parsing – the root object

  _root = [NSMutableDictionary new];

  //Put in the array as first the root object.

  [_axisAncestorOrSelf addObject:_root];

  //Create object for storing current element text value.

  _selfText = [NSMutableString new];

}

– (void)parserDidEndDocument:(NSXMLParser *)parser

{

  ///Clear unused object

  [_axisAncestorOrSelf removeLastObject];

}

– (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict

{

  ///Start processing of the current element

  _currentLevel++;

  if ([_axisAncestorOrSelf count] == _currentLevel)

  {

    //Add dictionary for started element if it not exist.

    [_axisAncestorOrSelf addObject:[NSMutableDictionary new]];

    //Processing a text value (if it exist) of the previous (parent) element.

    if ([_selfText length] > 0)

    {

      [AXIS_PARENT setObject:_selfText forKey:TEXT_NODE_KEY];

      _selfText = [NSMutableString new];

    }

  }

  //Add attribute values (if it exist) to current element.

  if ([attributeDict count] != 0)

  {

    for (id key in [attributeDict allKeys])

    {

      NSString *attributeKey = [NSString stringWithFormat:@”%@%@”, ATTRIBUTE_PREFIX, key];

      [AXIS_SELF setObject:attributeDict[key] forKey:attributeKey];

    }

  }

}

– (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string

{

  ///Processing the text value of the current element

  NSCharacterSet *characterSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];

  NSString *text = [string stringByTrimmingCharactersInSet: characterSet];

  [_selfText appendString:text];

}

– (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName

{

  ///Completion processing of the current element

  if ([AXIS_SELF count] == 0)

  {

    //If exist only text value of element – set it as element value.

    [AXIS_PARENT setObject:_selfText forKey:elementName];

    _selfText = [NSMutableString new];

  }

  else

  {

    if ([_selfText length] > 0)

    {

      //If exist text value of element and child elements – set it as child element value.

      [AXIS_SELF setObject:_selfText forKey:TEXT_NODE_KEY];

      _selfText = [NSMutableString new];

    }

    if (AXIS_PRECEDING_SIBLING)

    {

      if ([AXIS_PRECEDING_SIBLING isKindOfClass:[NSMutableArray class]])

      {

        //If exist collection of preceding-sibling elements – add current element to collection.

        [AXIS_PRECEDING_SIBLING addObject:AXIS_SELF];

      }

      else if ([AXIS_PRECEDING_SIBLING isKindOfClass:[NSMutableDictionary class]])

      {

        /*

         If exist only one preceding-sibling element – create collection

         and add both (preceding-sibling and current) elements to collection.

         */

        NSMutableArray *elementsArray = [NSMutableArray new];

        [elementsArray addObjectsFromArray:@[AXIS_PRECEDING_SIBLING, AXIS_SELF]];

        [AXIS_PARENT setObject:elementsArray forKey:elementName];

      }

    }

    else

    {

      //If preceding-sibling elements not exist – add current element as child element.

      [AXIS_PARENT setObject:AXIS_SELF forKey:elementName];

    }

    //Remove current element from storage for parsing elements.

    [_axisAncestorOrSelf removeObject:AXIS_SELF];

  }

  _currentLevel–;

}

#pragma mark – NSXMLParserDelegate Handling XML Errors

– (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError

{

  ///Handle parse error

  //Output in the console error.

  NSLog(@”Line:%i Column:%i – Parse Error Occurred: %@”, [parser lineNumber], [parser columnNumber], [parseError description]);

  //Set error prorerty pointer to parse error.

  _error = parseError;

}

– (void)parser:(NSXMLParser *)parser validationErrorOccurred:(NSError *)validationError

{

  ///Handle validation error

  //Output in the console error.

  NSLog(@”Line:%i Column:%i – Validation Error Occurred: %@”, [parser lineNumber], [parser columnNumber], [validationError description]);

  //Set error prorerty pointer to validation error.

  _error = validationError;

}

@end

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

//

//  AppDelegate.h

//  ContactsTestApp

#import <UIKit/UIKit.h>

@class ViewController1;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController1 *viewController;

@end

AppDelegate.m

#import “AppDelegate.h”

#import “ViewController1.h”

@implementation AppDelegate

@synthesize window = _window;

@synthesize viewController = _viewController;

– (void)dealloc

{

    [_window release];

    [_viewController release];

    [super dealloc];

}

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    // Override point for customization after application launch.

   // self.viewController = [[[ViewController alloc] initWithNibName:@”ViewController” bundle:nil] autorelease];

    

      self.viewController = [[[ViewController1 alloc] initWithNibName:@”ViewController1″ bundle:nil] autorelease];

    

    self.window.rootViewController = self.viewController;

    [self.window makeKeyAndVisible];

    return YES;

}

– (void)applicationWillResignActive:(UIApplication *)application

{

    /*

     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.

     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

     */

}

– (void)applicationDidEnterBackground:(UIApplication *)application

{

    /*

     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.

     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

     */

}

– (void)applicationWillEnterForeground:(UIApplication *)application

{

    /*

     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.

     */

}

– (void)applicationDidBecomeActive:(UIApplication *)application

{

    /*

     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

     */

}

– (void)applicationWillTerminate:(UIApplication *)application

{

    /*

     Called when the application is about to terminate.

     Save data if appropriate.

     See also applicationDidEnterBackground:.

     */

}

@end

ViewController1.h

#import <UIKit/UIKit.h>

@interface ViewController1 : UIViewController

{

    NSMutableArray *array;

    IBOutlet UITableView *table;

}

@end

ViewController1.m

#import “ViewController1.h”

#import “XMLConverter.h”

@interface ViewController1 ()

@end

@implementation ViewController1

– (void)viewDidLoad {

    [super viewDidLoad];

    

    array = [[NSMutableArray alloc] init];

    

    NSURL *url = [NSURL URLWithString:@”http://www.sandwell.gov.uk/rss/news&#8221;];

    [XMLConverter convertXMLURL:url completion:^(BOOL success, NSDictionary *dictionary, NSError *error) {

        NSLog(@”%@”,dictionary);

        array = [[[dictionary objectForKey:@”rss”] objectForKey:@”channel”] objectForKey:@”item”];

        [table reloadData];

        

    }];

    

    // Do any additional setup after loading the view from its nib.

}

#pragma mark – UITableViewDataSource And UITableViewDelegate

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

    return array.count;

}

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

    

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@”MyIdentifier”];

    

   

    if (cell == nil) {

        

       

        

        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@”MyIdentifier”] autorelease];

        

        cell.selectionStyle = UITableViewCellSelectionStyleNone;

        

        cell.textLabel.text =[[array objectAtIndex:indexPath.row] valueForKey:@”title”];

        

    }

  

    cell.textLabel.text = [[array objectAtIndex:indexPath.row] valueForKey:@”title”];

    return cell;

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

   

    

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

/*

@end

SkDatabase

/

//  SKDatabase.h

//  Version 1.1

//

//  Created by Shannon Appelcline on 9/11/08.

//  Copyright 2008 __MyCompanyName__. All rights reserved.

//

#import <UIKit/UIKit.h>

#import <sqlite3.h>

@protocol SKDatabaseDelegate <NSObject>

@optional

– (void)databaseTableWasUpdated:(NSString *)table;

@end

@interface SKDatabase : NSObject {

id<SKDatabaseDelegate> delegate;

sqlite3 *dbh;

BOOL dynamic;

}

@property id<SKDatabaseDelegate> delegate;

@property sqlite3 *dbh;

@property BOOL dynamic;

– (id)initWithFile:(NSString *)dbFile;

– (id)initWithDynamicFile:(NSString *)dbFile;

– (void)close;

– (sqlite3_stmt *)prepare:(NSString *)sql;

– (id)lookupColForSQL:(NSString *)sql;

– (NSDictionary *)lookupRowForSQL:(NSString *)sql;

– (NSArray *)lookupAllForSQL:(NSString *)sql;

– (NSMutableArray *)selectAll_1:(NSString *)where forTable:(NSString *)table;

– (int)lookupCountWhere:(NSString *)where forTable:(NSString *)table;

– (int)lookupMax:(NSString *)key Where:(NSString *)where forTable:(NSString *)table;

– (int)lookupSum:(NSString *)key Where:(NSString *)where forTable:(NSString *)table;

– (void)insertArray:(NSArray *)dbData forTable:(NSString *)table;

– (void)insertDictionary:(NSDictionary *)dbData forTable:(NSString *)table;

– (void)updateArray:(NSArray *)dbData forTable:(NSString *)table;

– (void)updateArray:(NSArray *)dbData forTable:(NSString *)table where:(NSString *)where;

– (void)updateDictionary:(NSDictionary *)dbData forTable:(NSString *)table;

– (void)updateDictionary:(NSDictionary *)dbData forTable:(NSString *)table where:(NSString *)where;

– (void)updateSQL:(NSString *)sql forTable:(NSString *)table;

– (void)deleteWhere:(NSString *)where forTable:(NSString *)table;

– (BOOL)runDynamicSQL:(NSString *)sql forTable:(NSString *)table;

– (void)deleteAllRowsForTable:(NSString *)table;

@end

#################################################

//

//  SKDatabase.m

//  Version 1.1

//

//  Created by Shannon Appelcline on 9/11/08.

//  Copyright 2008 __MyCompanyName__. All rights reserved.

//

#import “SKDatabase.h”

@implementation SKDatabase

@synthesize delegate;

@synthesize dbh;

@synthesize dynamic;

// Two ways to init: one if you’re just SELECTing from a database, one if you’re UPDATing

// and or INSERTing

– (id)initWithFile:(NSString *)dbFile {

if (self = [super init]) {

NSString *paths = [[NSBundle mainBundle] resourcePath];

NSString *path = [paths stringByAppendingPathComponent:dbFile];

int result = sqlite3_open([path UTF8String], &dbh);

NSAssert1(SQLITE_OK == result, NSLocalizedStringFromTable(@”Unable to open the sqlite database (%@).”, @”Database”, @””), [NSString stringWithUTF8String:sqlite3_errmsg(dbh)]);

self.dynamic = NO;

}

return self;

}

– (id)initWithDynamicFile:(NSString *)dbFile {

if (self = [super init]) {

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

NSString *docDir = [docPaths objectAtIndex:0];

NSString *docPath = [docDir stringByAppendingPathComponent:dbFile];

NSFileManager *fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:docPath]) {

NSString *origPaths = [[NSBundle mainBundle] resourcePath];

NSString *origPath = [origPaths stringByAppendingPathComponent:dbFile];

NSError *error;

int success = [fileManager copyItemAtPath:origPath toPath:docPath error:&error];

NSAssert1(success,[NSString stringWithString:@”Failed to copy database into dynamic location”],error);

}

int result = sqlite3_open([docPath UTF8String], &dbh);

NSAssert1(SQLITE_OK == result, NSLocalizedStringFromTable(@”Unable to open the sqlite database (%@).”, @”Database”, @””), [NSString stringWithUTF8String:sqlite3_errmsg(dbh)]);

self.dynamic = YES;

}

return self;

}

// Users should never need to call prepare

– (sqlite3_stmt *)prepare:(NSString *)sql {

const char *utfsql = [sql UTF8String];

sqlite3_stmt *statement;

if (sqlite3_prepare([self dbh],utfsql,-1,&statement,NULL) == SQLITE_OK) {

return statement;

} else {

return 0;

}

}

// Three ways to lookup results: for a variable number of responses, for a full row

// of responses, or for a singular bit of data

– (NSArray *)lookupAllForSQL:(NSString *)sql {

sqlite3_stmt *statement;

id result;

NSMutableArray *thisArray = [NSMutableArray arrayWithCapacity:4];

if ((statement = [self prepare:sql])) {

while (sqlite3_step(statement) == SQLITE_ROW) {

NSMutableDictionary *thisDict = [NSMutableDictionary dictionaryWithCapacity:4];

for (int i = 0 ; i < sqlite3_column_count(statement) ; i++) {

if (sqlite3_column_decltype(statement,i) != NULL &&

strcasecmp(sqlite3_column_decltype(statement,i),“Boolean”) == 0) {

result = [NSNumber numberWithBool😦BOOL)sqlite3_column_int(statement,i)];

} else if (sqlite3_column_type(statement, i) == SQLITE_TEXT) {

result = [NSString stringWithUTF8String😦char *)sqlite3_column_text(statement,i)];

} else if (sqlite3_column_type(statement,i) == SQLITE_INTEGER) {

result = [NSNumber numberWithInt😦int)sqlite3_column_int(statement,i)];

} else if (sqlite3_column_type(statement,i) == SQLITE_FLOAT) {

result = [NSNumber numberWithFloat😦float)sqlite3_column_double(statement,i)];

} else {

result = [NSString stringWithUTF8String😦char *)sqlite3_column_text(statement,i)];

}

if (result) {

[thisDict setObject:result

forKey:[NSString stringWithUTF8String:sqlite3_column_name(statement,i)]];

}

}

[thisArray addObject:[NSDictionary dictionaryWithDictionary:thisDict]];

}

}

sqlite3_finalize(statement);

return thisArray;

}

– (NSDictionary *)lookupRowForSQL:(NSString *)sql {

sqlite3_stmt *statement;

id result;

NSMutableDictionary *thisDict = [NSMutableDictionary dictionaryWithCapacity:4];

if ((statement = [self prepare:sql])) {

if (sqlite3_step(statement) == SQLITE_ROW) {

for (int i = 0 ; i < sqlite3_column_count(statement) ; i++) {

if (strcasecmp(sqlite3_column_decltype(statement,i),“Boolean”) == 0) {

result = [NSNumber numberWithBool😦BOOL)sqlite3_column_int(statement,i)];

} else if (sqlite3_column_type(statement, i) == SQLITE_TEXT) {

result = [NSString stringWithUTF8String😦char *)sqlite3_column_text(statement,i)];

} else if (sqlite3_column_type(statement,i) == SQLITE_INTEGER) {

result = [NSNumber numberWithInt😦int)sqlite3_column_int(statement,i)];

} else if (sqlite3_column_type(statement,i) == SQLITE_FLOAT) {

result = [NSNumber numberWithFloat😦float)sqlite3_column_double(statement,i)];

} else {

result = [NSString stringWithUTF8String😦char *)sqlite3_column_text(statement,i)];

}

if (result) {

[thisDict setObject:result

forKey:[NSString stringWithUTF8String:sqlite3_column_name(statement,i)]];

}

}

}

}

sqlite3_finalize(statement);

return thisDict;

}

– (id)lookupColForSQL:(NSString *)sql {

sqlite3_stmt *statement;

id result;

if ((statement = [self prepare:sql])) {

if (sqlite3_step(statement) == SQLITE_ROW) {

if (strcasecmp(sqlite3_column_decltype(statement,0),“Boolean”) == 0) {

result = [NSNumber numberWithBool😦BOOL)sqlite3_column_int(statement,0)];

} else if (sqlite3_column_type(statement, 0) == SQLITE_TEXT) {

result = [NSString stringWithUTF8String😦char *)sqlite3_column_text(statement,0)];

} else if (sqlite3_column_type(statement,0) == SQLITE_INTEGER) {

result = [NSNumber numberWithInt😦int)sqlite3_column_int(statement,0)];

} else if (sqlite3_column_type(statement,0) == SQLITE_FLOAT) {

result = [NSNumber numberWithDouble😦double)sqlite3_column_double(statement,0)];

} else {

result = [NSString stringWithUTF8String😦char *)sqlite3_column_text(statement,0)];

}

}

}

sqlite3_finalize(statement);

return result;

}

// Select All

-(NSMutableArray *)selectAll_1:(NSString *)where forTable:(NSString *)table

{

NSString *sql = [NSString stringWithFormat:@”SELECT * FROM %@ WHERE %@”,table,where];    

sqlite3_stmt *statement;

if ((statement = [self prepare:sql])) {

NSMutableDictionary *dict;

NSMutableArray *DataArr = [[NSMutableArray alloc] init];

while(sqlite3_step(statement) == SQLITE_ROW)

{

dict = [[NSMutableDictionary alloc] init];

int ID = (sqlite3_column_int(statement,0));

NSString *nm = [NSString stringWithUTF8String😦const char *)sqlite3_column_text(statement,1)];

// NSString *nm1 = [NSString stringWithUTF8String:(const char *)sqlite3_column_text(statement,0)];

[dict setObject:[NSString stringWithFormat:@”%d”, ID] forKey:@”CatId”];

[dict setObject:nm forKey:@”CatName”];

[DataArr addObject:dict];

//[dict release];

}

return DataArr;

}

return nil;

}

// Simple use of COUNTS, MAX, etc.

– (int)lookupCountWhere:(NSString *)where forTable:(NSString *)table {

int tableCount = 0;

NSString *sql = [NSString stringWithFormat:@”SELECT COUNT(*) FROM %@ WHERE %@”,

table,where];    

sqlite3_stmt *statement;

if ((statement = [self prepare:sql]))

    {

if (sqlite3_step(statement) == SQLITE_ROW) {

tableCount = sqlite3_column_int(statement,0);

}

}

sqlite3_finalize(statement);

return tableCount;

}

– (int)lookupMax:(NSString *)key Where:(NSString *)where forTable:(NSString *)table {

int tableMax = 0;

NSString *sql = [NSString stringWithFormat:@”SELECT MAX(%@) FROM %@ WHERE %@”,

key,table,where];    

sqlite3_stmt *statement;

if ((statement = [self prepare:sql])) {

if (sqlite3_step(statement) == SQLITE_ROW) {

tableMax = sqlite3_column_int(statement,0);

}

}

sqlite3_finalize(statement);

return tableMax;

}

– (int)lookupSum:(NSString *)key Where:(NSString *)where forTable:(NSString *)table {

int tableSum = 0;

NSString *sql = [NSString stringWithFormat:@”SELECT SUM(%@) FROM %@ WHERE %@”,

key,table,where];    

sqlite3_stmt *statement;

if ((statement = [self prepare:sql])) {

if (sqlite3_step(statement) == SQLITE_ROW) {

tableSum = sqlite3_column_int(statement,0);

}

}

sqlite3_finalize(statement);

return tableSum;

}

// INSERTing and UPDATing

– (void)insertArray:(NSArray *)dbData forTable:(NSString *)table {

NSLog(@”%@”,dbData);

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

{

NSDictionary *dict=[dbData objectAtIndex:i];

NSMutableString *sql = [NSMutableString stringWithCapacity:16];

[sql appendFormat:@”INSERT INTO %@ (“,table];

NSArray *dataKeys = [dict allKeys];

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

[sql appendFormat:@”%@”,[dataKeys objectAtIndex:i]];

if (i + 1 < [dataKeys count]) {

[sql appendFormat:@”, “];

}

}

[sql appendFormat:@”) VALUES(“];

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

//if ([[dict objectForKey:[dataKeys objectAtIndex:i]] intValue]) {

// [sql appendFormat:@”%@”,[dict objectForKey:[dataKeys objectAtIndex:i]]];

//} else {

[sql appendFormat:@”‘%@'”,[dict objectForKey:[dataKeys objectAtIndex:i]]];

//}

if (i + 1 < [dict count]) {

[sql appendFormat:@”, “];

}

}

[sql appendFormat:@”)”];

NSLog(sql);

[self runDynamicSQL:sql forTable:table];

}

}

– (void)insertDictionary:(NSDictionary *)dbData forTable:(NSString *)table {

NSMutableString *sql = [NSMutableString stringWithCapacity:16];

[sql appendFormat:@”INSERT INTO %@ (“,table];

NSArray *dataKeys = [dbData allKeys];

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

[sql appendFormat:@”%@”,[dataKeys objectAtIndex:i]];

if (i + 1 < [dbData count]) {

[sql appendFormat:@”, “];

}

}

[sql appendFormat:@”) VALUES(“];

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

//NSString *tempStr = [dbData objectForKey:[dataKeys objectAtIndex:i]];

//int temp = [tempStr intValue];

//if (temp)

//{

//[sql appendFormat:@”%@”,[dbData objectForKey:[dataKeys objectAtIndex:i]]];

//} else {

[sql appendFormat:@”‘%@'”,[dbData objectForKey:[dataKeys objectAtIndex:i]]];

//}

if (i + 1 < [dbData count]) {

[sql appendFormat:@”, “];

}

}

[sql appendFormat:@”)”];

NSLog(sql);

[self runDynamicSQL:sql forTable:table];

}

– (void)updateArray:(NSArray *)dbData forTable:(NSString *)table {

[self updateArray:dbData forTable:table where:NULL];

}

– (void)updateArray:(NSArray *)dbData forTable:(NSString *)table where:(NSString *)where {

NSMutableString *sql = [NSMutableString stringWithCapacity:16];

[sql appendFormat:@”UPDATE %@ SET “,table];

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

if ([[[dbData objectAtIndex:i] objectForKey:@”value”] intValue]) {

[sql appendFormat:@”%@=%@”,

[[dbData objectAtIndex:i] objectForKey:@”key”],

[[dbData objectAtIndex:i] objectForKey:@”value”]];

} else {

[sql appendFormat:@”%@=’%@'”,

[[dbData objectAtIndex:i] objectForKey:@”key”],

[[dbData objectAtIndex:i] objectForKey:@”value”]];

}

if (i + 1 < [dbData count]) {

[sql appendFormat:@”, “];

}

}

if (where != NULL) {

[sql appendFormat:@” WHERE %@”,where];

} else {

[sql appendFormat:@” WHERE 1″,where];

}

[self runDynamicSQL:sql forTable:table];

}

– (void)updateDictionary:(NSDictionary *)dbData forTable:(NSString *)table {

[self updateDictionary:dbData forTable:table where:NULL];

}

– (void)updateDictionary:(NSDictionary *)dbData forTable:(NSString *)table where:(NSString *)where {

NSMutableString *sql = [NSMutableString stringWithCapacity:16];

[sql appendFormat:@”UPDATE %@ SET “,table];

NSArray *dataKeys = [dbData allKeys];

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

// if ([[dbData objectForKey:[dataKeys objectAtIndex:i]] intValue]) {

// [sql appendFormat:@”%@=’%@'”,

// [dataKeys objectAtIndex:i],

// [dbData objectForKey:[dataKeys objectAtIndex:i]]];

// } else {

[sql appendFormat:@”%@=’%@'”,

[dataKeys objectAtIndex:i],

[dbData objectForKey:[dataKeys objectAtIndex:i]]];

if (i + 1 < [dbData count]) {

[sql appendFormat:@”, “];

}

}

if (where != NULL) {

[sql appendFormat:@” WHERE %@”,where];

}

NSLog(@”%@”,sql);

[self runDynamicSQL:sql forTable:table];

}

– (void)updateSQL:(NSString *)sql forTable:(NSString *)table {

[self runDynamicSQL:sql forTable:table];

}

– (void)deleteWhere:(NSString *)where forTable:(NSString *)table {

NSString *sql = [NSString stringWithFormat:@”DELETE FROM %@ WHERE %@”,

table,where];

    

    NSLog(@”%@”,sql);

[self runDynamicSQL:sql forTable:table];

}

– (void)deleteAllRowsForTable:(NSString *)table {

NSString *sql = [NSString stringWithFormat:@”DELETE FROM %@”,table];

[self runDynamicSQL:sql forTable:table];

}

// INSERT/UPDATE/DELETE Subroutines

– (BOOL)runDynamicSQL:(NSString *)sql forTable:(NSString *)table {

int result;

NSAssert1(self.dynamic == 1,[NSString stringWithString:@”Tried to use a dynamic function on a static database”],NULL);

sqlite3_stmt *statement;

if ((statement = [self prepare:sql])) {

result = sqlite3_step(statement);

    }

sqlite3_finalize(statement);

if (result)

{

if (self.delegate != NULL && [self.delegate respondsToSelector:@selector(databaseTableWasUpdated:)])

{

[delegate databaseTableWasUpdated:table];

}

return YES;

} else {

return NO;

}

}

// requirements for closing things down

– (void)dealloc {

[self close];

//[delegate release];

//[super dealloc];

}

– (void)close {

if (dbh) {

sqlite3_close(dbh);

}

}

@end

//

//  ViewController.h

//  SKDATABASE

//

//  Created by Moweb_11 on 06/01/15.

//  Copyright (c) 2015 Moweb_11. All rights reserved.

//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController{

    

    

    IBOutlet UITextField *txtId;

    IBOutlet UITextField *txtNm;

    IBOutlet UITextField *txtAge;

    

    IBOutlet UITableView *tblData;

    

    NSArray *arryData;

}

– (IBAction)mthSave:(id)sender;

@end

//

//  ViewController.m

//  SKDATABASE

//

//  Created by Moweb_11 on 06/01/15.

//  Copyright (c) 2015 Moweb_11. All rights reserved.

//

#import “ViewController.h”

#import “AppDelegate.h”

#import “SKDatabase.h”

@interface ViewController ()

@end

@implementation ViewController

– (void)viewDidLoad {

    [super viewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

    

    

    

}

– (IBAction)mthSave:(id)sender{

    

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

    

    // Insert record

   // NSString *queryInsert=[NSString stringWithFormat:@”insert into tblEmp values(‘%@’, ‘%@’, ‘%@’)”, txtId.text, txtNm.text,txtAge.text];

    

    

    NSMutableDictionary *dictdata=[[NSMutableDictionary alloc]init];

    [dictdata setObject:txtId.text forKey:@”ID”];

    [dictdata setObject:txtNm.text forKey:@”Name”];

    [dictdata setObject:txtAge.text forKey:@”Age”];

    

    NSMutableArray  *arryData1 = [[NSMutableArray alloc] initWithObjects:dictdata, nil];

    

    [appDelegate.objSkData insertArray:arryData1 forTable:@”tblEmp”];

    

    

     arryData=[appDelegate.objSkData lookupAllForSQL:@”Select * from tblEmp”];

    NSLog(@”DATA%@”,arryData);

    [tblData reloadData];

}

#pragma mark – UITableView method implementation

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;

}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return [arryData count];

}

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

    // Dequeue the cell.

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@”idCellRecord”];

    

    if (cell==nil)

    {

        cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@”idCellRecord”];

    }

   // NSInteger indexOfFirstname = [self.dbManager.arrColumnNames indexOfObject:@”ID”];

   // NSInteger indexOfLastname = [self.dbManager.arrColumnNames indexOfObject:@”Name”];

    //NSInteger indexOfAge = [self.dbManager.arrColumnNames indexOfObject:@”Age”];

    

    // Set the loaded data to the appropriate cell labels.

    cell.textLabel.text = [NSString stringWithFormat:@”%@”,[[arryData objectAtIndex:indexPath.row] objectForKey:@”Age”]];

    

    cell.detailTextLabel.text = [NSString stringWithFormat:@”%@”,[[arryData objectAtIndex:indexPath.row] objectForKey:@”ID”]];

    cell.detailTextLabel.textColor = [UIColor blackColor];

    tableView.backgroundColor= [UIColor redColor];

    cell.backgroundColor = [UIColor redColor];

    return cell;

}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

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

    if (editingStyle == UITableViewCellEditingStyleDelete) {

        // Delete the selected record.

        // Find the record ID.

        int recordIDToDelete = [[[arryData objectAtIndex:indexPath.row] objectForKey:@”ID”] intValue];

        

        // Prepare the query.

        NSString *query = [NSString stringWithFormat:@”ID=%d”, recordIDToDelete];

        

        // Execute the query.

        //[self.dbManager executeQuery:query];

        

        [appDelegate.objSkData deleteWhere:query forTable:@”tblEmp”];

        

    

        arryData=[[NSArray alloc]init];

        

        

        arryData=[appDelegate.objSkData lookupAllForSQL:@”Select * from tblEmp”];

        // Reload the table view.

        [tblData reloadData];

    }

}

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

    return 60.0;

}

– (void)didReceiveMemoryWarning {

    [super didReceiveMemoryWarning];

    // Dispose of any resources that can be recreated.

}

@end

UtilityLibrary.h

UtilityLibrary.h

#import <Foundation/Foundation.h>

#import “AFHTTPRequestOperationManager.h”

#import “AFURLSessionManager.h”

#import <Social/Social.h>

#import <Accounts/Accounts.h>

#import <StoreKit/StoreKit.h>

#define kInAppPurchaseManagerProductsFetchedNotification @“kInAppPurchaseManagerProductsFetchedNotification”

#define kInAppPurchaseManagerTransactionFailedNotification @“kInAppPurchaseManagerTransactionFailedNotification”

#define kInAppPurchaseManagerTransactionSucceededNotification @“kInAppPurchaseManagerTransactionSucceededNotification”

// 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;

-(void)transactionResponce:(BOOL)result withTransactionObject:(SKPaymentTransaction *)transaction;

@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)uploadWithURL:(NSString *)str andfilePath:(NSString *)path 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;

-(void)uploadMultipleFileWithURL2:(NSString *)str andfilePath:(NSString *)pathArray andVideoPath:(NSString *)videoPath andName:(NSString *)controlName fileName:(NSString *)name 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;

//Getting facebook permission, user info and pic

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

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

//Getting list of facebook friends

-(void)getFriendListWithSorting:(BOOL)enableSort account:(ACAccount *)faceBookAccount;

– (void)loadStore;

– (BOOL)canMakePurchases;

-(BOOL) hasPurchasedProductIdentifier:(NSString *)productIdentifier;

– (void)purchaseProUpgrade:(NSString *)productIdentifier;

– (NSString *)localizedPrice:(SKProduct *)product;

– (void)requestProductDataWithArray:(NSArray *)productsIdentifiers OnCompletion:(void (^)(NSArray *purchasableProducts))completionBlock;

-(SKProduct *)productForProductIdentifier:(NSString *)productIdentifier;

@end

UtilityLibrary.m

#import “UtilityLibrary.h”

#define kInAppPurchaseProUpgradeProductId @“com.runmonster.runmonsterfree.upgradetopro”

@interface UtilityLibrary()

{

    

}

@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];

    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];

        NSLog(@”%@”,jsonString);

        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(json);

             

         }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];

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

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

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

     {

         NSData *responce = responseObject;

         

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

         

         if (json == nil)

         {

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

         }

         successResponce(json);

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

    {

        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)

    {

        NSLog(@”File downloaded to: %@”, filePath);

        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];

}

– (void)multipartFormRequestWithMethod:(NSString *)method

                                                   path:(NSString *)path

                                             parameters:(NSDictionary *)parameters

                              constructingBodyWithBlock:(void (^)(id <AFMultipartFormData>formData))block{

    

    

    

    

    

}

#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];

    

    if(![path isEqualToString:@””])

    {

        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];

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

         

         successResponce(json);

         

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

     {

         failureResponce(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];

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

    

    NSLog(@”FILEPATHINRESPONCE=>%@”,filePath);

    [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:@”recipeImage[%d]”,i]

                                         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)

     {

         failureResponce(error);

     }];

}

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

{

    managerObject.responseSerializer = [AFHTTPResponseSerializer serializer];

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

    

    NSLog(@”FILEPATHINRESPONCE=>%@”,filePath);

    [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];

             

             

             NSData  *imgData = [NSData dataWithContentsOfFile:videoPath];

             [formData appendPartWithFileData:imgData

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

                                     fileName:[NSString stringWithFormat:@”coverImage.png”]

                                     mimeType:@”image/png”];

         }

         

         if ([pathArray isKindOfClass:[NSString class]])

         {

             if (pathArray.length>0)

             {

                 NSData  *imgData = [NSData dataWithContentsOfFile:pathArray];

                 [formData appendPartWithFileData:imgData

                                             name:[NSString stringWithFormat:@”coverImage”]

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

                                         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)

     {

         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)liking:(ACAccount *)account

{

    

    managerObject.responseSerializer = [AFHTTPResponseSerializer serializer];

    NSDictionary *params = @{@”access_token” : account.credential.oauthToken};

    [managerObject POST:@”https://graph.facebook.com/244587955553836/likes&#8221; parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)

     {

        // NSData *responce = responseObject;

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

         

         

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

     {

         NSLog(@”%@”,error);

     }];

}

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

{

    NSString *facebookAppId = appKeyId;

    

    NSArray *facebookPermission = @[@”read_stream”,@”email”];

    

    NSDictionary *facebookOptions = @{ACFacebookAppIdKey : facebookAppId,

                                      ACFacebookPermissionsKey : facebookPermission,

                                      ACFacebookAudienceKey : ACFacebookAudienceFriends};

    

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

    

    ACAccountType *facebookType = [facebookStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

    

    [facebookStore requestAccessToAccountsWithType:facebookType options:facebookOptions completion:^(BOOL granted, NSError *error)

     {

         if (granted)

         {

             

             NSArray *faceBookPermission = @[@”publish_stream”,@”publish_actions”];

             

             NSDictionary *faceBookOptions = @{ACFacebookAppIdKey : facebookAppId,

                                               ACFacebookAudienceKey : ACFacebookAudienceFriends,

                                               ACFacebookPermissionsKey : faceBookPermission};

             

             [facebookStore requestAccessToAccountsWithType:facebookType options:faceBookOptions completion:^(BOOL grantedPublishing, NSError *error)

              {

                  

                  if (grantedPublishing)

                  {

                      

                      ACAccount *faceBookAccount = [[ACAccount alloc] initWithAccountType:facebookType];

                      

                      NSArray *arrayOfAccounts = [facebookStore accountsWithAccountType:facebookType];

                      

                      faceBookAccount = [arrayOfAccounts lastObject];

                      

                      if (list)

                      {

                          [self getFriendListWithSorting:YES account:faceBookAccount success:^(id response, NSString* tagstr)

                           {

                               successResponce(response,tagstr);

                           }failure:^(NSError *error)

                           {

                               failureResponce(error);

                           }];

                      }

                      

                      if (wantUserInfo)

                      {

                          NSURL *meurl = [NSURL URLWithString:@”https://graph.facebook.com/me&#8221;];

                          

                          SLRequest *merequest = [SLRequest requestForServiceType:SLServiceTypeFacebook

                                                                    requestMethod:SLRequestMethodGET

                                                                              URL:meurl

                                                                       parameters:nil];

                          

                          merequest.account = faceBookAccount;

                          [merequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)

                           {

                               if (error == nil)

                               {

                                   //NSString *meDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

                                   

                                   NSMutableDictionary *dict = [[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil] mutableCopy]; //[[meDataString JSONValue] mutableCopy];

                                   

                                   [dict setObject:faceBookAccount forKey:@”accountObject”];

                                   //                              / [self liking:faceBookAccount];

                                   

                                   if (wantProfilePic)

                                   {

                                       NSString *urlStringPic = [NSString stringWithFormat:@”https://graph.facebook.com/%@/picture?type=normal&#8221;,[NSString stringWithFormat:@”%@”,[dict objectForKey:@”id”]]];

                                       //NSURL *meProfilePicurl = [NSURL URLWithString:urlStringPic];

                                       

                                       [dict setObject:urlStringPic forKey:@”fbuserPic”];

                                       

                                       //[delegate Responce:dict withRequestTag:@”facebook_userdetails” andInfodictionary:nil];

                                       successResponce(dict,@”facebook_userdetails”);

                                       

                                       //                                   SLRequest *merequestPic = [SLRequest requestForServiceType:SLServiceTypeFacebook

                                       //                                                                                requestMethod:SLRequestMethodGET

                                       //                                                                                          URL:meProfilePicurl

                                       //                                                                                   parameters:nil];

                                       //

                                       //                                   merequestPic.account = faceBookAccount;

                                       //                                   [merequestPic performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)

                                       //                                    {

                                       //                                        NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

                                       //

                                       //                                        path = [NSString stringWithFormat:@”%@/facebookuserpic.jpeg”,path];

                                       //

                                       //                                        [responseData writeToFile:path atomically:YES];

                                       //

                                       //                                        [dict setObject:path forKey:@”fbuserPic”];

                                       //

                                       //                                        [delegate Responce:dict withRequestTag:@”facebook_userdetails” andInfodictionary:nil];

                                       //                                    }];

                                       

                                       

                                       

                                   }

                                   else

                                   {

                                       if ([dict objectForKey:@”error”] == nil)

                                       {

                                           //[delegate Responce:dict withRequestTag:@”facebook_userdetails” andInfodictionary:nil];

                                           successResponce(dict,@”facebook_userdetails”);

                                       }

                                       else

                                       {

                                           if ([[NSString stringWithFormat:@”%@”,[[dict objectForKey:@”error”] objectForKey:@”code”]] isEqualToString:@”190″])

                                           {

                                               [self renewingCredentialsWithaccount:facebookStore andAccountType:faceBookAccount wantUserInfo:wantUserInfo andPic:wantProfilePic success:^(id response, NSString *tgstr)

                                                {

                                                    successResponce(response,tgstr);

                                                }failure:^(NSError *error)

                                                {

                                                    failureResponce(error);

                                                }];

                                           }

                                       }

                                       

                                   }

                               }

                               else

                               {

                                  // [delegate errorOccured:error];

                                   failureResponce(error);

                               }

                               

                               

                           }];

                      }

                      else

                      {

                          //[delegate Responce:faceBookAccount withRequestTag:@”facebook_account” andInfodictionary:nil];

                          successResponce(faceBookAccount,@”facebook_account”);

                      }

                      

                      

                  }

                  else if (!grantedPublishing)

                  {

                      NSLog(@”Publish permission error: %@”, [error localizedDescription]);

                      failureResponce(error);

                      

                  }

                  

              }

              ];

             

             

         }

         

         else if (!granted)

         {

             NSLog(@”Read permission error: %@”, [error localizedDescription]);

             if ([[error localizedDescription] isEqualToString:@”The operation couldn’t be completed. (com.apple.accounts error 6.)”])

             {

                 [self performSelectorOnMainThread:@selector(showError) withObject:error waitUntilDone:NO];

                 //[delegate errorOccured:nil];

                 

             }

             failureResponce(error);

             

         }

         

         

     }];

    

}

-(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];

             NSLog(@”%@”,twAccount.username);

             // 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.

                      NSLog(@”HTTP Response: %i”, [urlResponse statusCode]);

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

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

                      

                      NSLog(@”%@”, jsonResponse);

                      

                     // [delegate Responce:jsonResponse withRequestTag:@”twitter” andInfodictionary: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

             

         {

             NSLog(@”Permission Not Granted”);

             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;

             NSLog(@”Error: %@”, error);

             //[delegate errorOccured:nil];

             failureResponce(error);

         }

     }];

    

    // Tidy up

    twitter = nil;

    twAccountType = nil;

}

-(void)showError

{

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

    [alert show];

    alert = nil;

}

-(void) renewingCredentialsWithaccount:(ACAccountStore *)accountStore andAccountType:(ACAccount *)faceBookAccount wantUserInfo:(BOOL)user andPic:(BOOL)picUser success:(void(^)(id responce, NSString *tagstr))successResponce failure:(void(^)(NSError *error))failureResponce

{

    if (faceBookAccount) {

        [accountStore renewCredentialsForAccount:faceBookAccount completion:^(ACAccountCredentialRenewResult renewResult, NSError *error)

         {

             

             switch (renewResult) {

                 case ACAccountCredentialRenewResultRenewed:

                 {

                     if (user)

                     {

                         NSURL *meurl = [NSURL URLWithString:@”https://graph.facebook.com/me&#8221;];

                         

                         SLRequest *merequest = [SLRequest requestForServiceType:SLServiceTypeFacebook

                                                                   requestMethod:SLRequestMethodGET

                                                                             URL:meurl

                                                                      parameters:nil];

                         

                         merequest.account = faceBookAccount;

                         [merequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)

                          {

//                              NSString *meDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

                              

                              NSMutableDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:nil];

                              

                              if (picUser)

                              {

                                  NSString *urlStringPic = [NSString stringWithFormat:@”https://graph.facebook.com/%@/picture&#8221;,[NSString stringWithFormat:@”%@”,[dict objectForKey:@”id”]]];

                                  NSURL *meProfilePicurl = [NSURL URLWithString:urlStringPic];

                                  

                                  

                                  SLRequest *merequestPic = [SLRequest requestForServiceType:SLServiceTypeFacebook

                                                                               requestMethod:SLRequestMethodGET

                                                                                         URL:meProfilePicurl

                                                                                  parameters:nil];

                                  

                                  merequestPic.account = faceBookAccount;

                                  [merequestPic performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)

                                   {

                                       NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

                                       

                                       path = [NSString stringWithFormat:@”%@/facebookuserpic.jpeg”,path];

                                       

                                       [responseData writeToFile:path atomically:YES];

                                       

                                       [dict setObject:path forKey:@”fbuserPic”];

                                       

                                       //[delegate Responce:dict withRequestTag:@”facebook_userdetails” andInfodictionary:nil];

                                       successResponce(dict,@”facebook_userdetails”);

                                   }];

                                  

                                  

                                  

                              }

                              else

                              {

                                  if ([dict objectForKey:@”error”] == nil)

                                  {

                                    //  [delegate Responce:dict withRequestTag:@”facebook_userdetails” andInfodictionary:nil];

                                      successResponce(dict,@”facebook_userdetails”);

                                  }

                                  else

                                  {

                                      if ([[NSString stringWithFormat:@”%@”,[[dict objectForKey:@”error”] objectForKey:@”code”]] isEqualToString:@”190″])

                                      {

                                          [self showError];

                                          [delegate errorOccured:nil];

                                          failureResponce(error);

                                      }

                                  }

                                  

                              }

                              

                              

                          }];

                     }

                 }break;

                 case ACAccountCredentialRenewResultFailed:

                 {

                     NSLog(@”Renewed Failed”);

                 }break;

                 case ACAccountCredentialRenewResultRejected:

                 {

                     NSLog(@”Renewed Rejected”);

                 }

                 default:

                     break;

             }

             

         }];

    }

}

#pragma mark –

#pragma mark get facebook friends list

-(void)getFriendListWithSorting:(BOOL)enableSort account:(ACAccount *)faceBookAccount success:(void(^)(id responce, NSString *tagstr))successResponce failure:(void(^)(NSError *error))failureResponce

{

    // Create the URL to the end point

    NSURL *friendsList = [NSURL URLWithString:@”https://graph.facebook.com/me/friends&#8221;];

    

    // Create the SLReqeust

    SLRequest *getFriends = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodGET URL:friendsList parameters:nil];

    

    

    getFriends.account = faceBookAccount;

    

    // Perform the request

    [getFriends performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {

        if (error)

        {

            // If there is an error we populate the error string with error

            

            NSLog(@”Error: %@”, [NSString stringWithFormat:@”%@”, [error localizedDescription]]);

            failureResponce(error);

        } else

        {

            NSLog(@”HTTP Response: %i”, [urlResponse statusCode]);

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

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

           // [delegate Responce:jsonResponse withRequestTag:@”facebook_friendlist” andInfodictionary:nil];

            successResponce(jsonResponse,@”facebook_friendlist”);

            // Tidy Up

            jsonResponse = nil;

        }

    }];

    

    // Tidy Up

    getFriends = nil;

    friendsList = nil;

}

//++++++++++++++++++++InApp Purchase++++++++++++++++++++++++++++++

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

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

#pragma mark getting product details

– (void)requestProductDataWithArray:(NSArray *)productsIdentifiers OnCompletion:(void (^)(NSArray *purchasableProducts))completionBlock;

{

    self.getProducts = completionBlock;

    NSSet *productIds = [NSSet setWithArray:productsIdentifiers];

    SKProductsRequest *productsRequest = [[SKProductsRequest alloc] initWithProductIdentifiers:productIds];

    productsRequest.delegate = (id)self;

    [productsRequest start];

}

-(SKProduct *)productForProductIdentifier:(NSString *)productIdentifier

{

    SKProduct *returnProduct = nil;

    for (SKProduct *product in arrayAvailableProducts)

    {

        if ([product.productIdentifier isEqualToString:productIdentifier])

        {

            returnProduct = product;

        }

    }

    return returnProduct;

}

– (NSString *)localizedPrice:(SKProduct *)product

{

    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];

    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];

    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];

    [numberFormatter setLocale:product.priceLocale];

    NSString *formattedString = [numberFormatter stringFromNumber:product.price];

    return formattedString;

}

#pragma mark Store Coding

– (void)loadStore

{

    // restarts any purchases if they were interrupted last time the app was open

    [[SKPaymentQueue defaultQueue] addTransactionObserver😦id)self];

    

}

– (BOOL)canMakePurchases

{

    return [SKPaymentQueue canMakePayments];

}

-(BOOL) hasPurchasedProductIdentifier:(NSString *)productIdentifier

{

    return ([[NSUserDefaults standardUserDefaults] boolForKey:productIdentifier]);

}

//

// kick off the upgrade transaction

//

– (void)purchaseProUpgrade:(NSString *)productIdentifier;

{

    SKProduct *product = [self productForProductIdentifier:productIdentifier];

    SKPayment *payment = [SKPayment paymentWithProduct:product];

    [[SKPaymentQueue defaultQueue] addPayment:payment];

}

#pragma mark –

#pragma mark SKProductsRequestDelegate methods

– (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response

{

    //    NSArray *products = response.products;

    //    if ([products count]==1)

    //    {

    //        proUpgradeProduct = [[products firstObjectCommonWithArray:products] retain];

    //    }

    //    else

    //    {

    //        proUpgradeProduct = nil;

    //    }

    //

    //    if (proUpgradeProduct)

    //    {

    //        NSLog(@”Product title: %@” , proUpgradeProduct.localizedTitle);

    //        NSLog(@”Product description: %@” , proUpgradeProduct.localizedDescription);

    //        NSLog(@”Product price: %@” , proUpgradeProduct.price);

    //        NSLog(@”Product id: %@” , proUpgradeProduct.productIdentifier);

    //    }

    //

    //    for (NSString *invalidProductId in response.invalidProductIdentifiers)

    //    {

    //        NSLog(@”Invalid product id: %@” , invalidProductId);

    //    }

    //

    //    // finally release the reqest we alloc/init’ed in requestProUpgradeProductData

    //    [request release];

    //

    //    [[NSNotificationCenter defaultCenter] postNotificationName:kInAppPurchaseManagerProductsFetchedNotification object:self userInfo:nil];

    

    arrayAvailableProducts = response.products;

    self.getProducts(response.products);

    

}

#pragma mark –

#pragma mark Purchase helpers

//

// saves a record of the transaction by storing the receipt to disk

//

– (void)recordTransaction:(SKPaymentTransaction *)transaction

{

    if ([transaction.payment.productIdentifier isEqualToString:kInAppPurchaseProUpgradeProductId])

    {

        // save the transaction receipt to disk

        [[NSUserDefaults standardUserDefaults] setValue:transaction.transactionReceipt forKey:@”proUpgradeTransactionReceipt” ];

        [[NSUserDefaults standardUserDefaults] synchronize];

    }

}

//

// enable pro features

//

– (void)provideContent:(NSString *)purchasedProductID forTransaction:(SKPaymentTransaction *)transaction receiptData:(NSData *)receiptData

{

    

    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:purchasedProductID];

    [[NSUserDefaults standardUserDefaults] synchronize];

    if ([purchasedProductID isEqualToString:kInAppPurchaseProUpgradeProductId])

    {

        // enable the pro features

        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@”isProUpgradePurchased” ];

        [[NSUserDefaults standardUserDefaults] synchronize];

    }

}

//

// removes the transaction from the queue and posts a notification with the transaction result

//

– (void)finishTransaction:(SKPaymentTransaction *)transaction wasSuccessful:(BOOL)wasSuccessful

{

    // remove the transaction from the payment queue.

    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

    

//    NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:transaction, @”transaction” , nil];

    [delegate transactionResponce:wasSuccessful withTransactionObject:transaction];

}

//

// called when the transaction was successful

//

– (void)completeTransaction:(SKPaymentTransaction *)transaction

{

    [self recordTransaction:transaction];

    [self provideContent:transaction.payment.productIdentifier forTransaction:transaction receiptData:transaction.transactionReceipt];

    [self finishTransaction:transaction wasSuccessful:YES];

}

//

// called when a transaction has been restored and and successfully completed

//

– (void)restoreTransaction:(SKPaymentTransaction *)transaction

{

    [self recordTransaction:transaction.originalTransaction];

    [self provideContent:transaction.payment.productIdentifier forTransaction:transaction receiptData:transaction.transactionReceipt];

    [self finishTransaction:transaction wasSuccessful:YES];

}

//

// called when a transaction has failed

//

– (void)failedTransaction:(SKPaymentTransaction *)transaction

{

    if (transaction.error.code != SKErrorPaymentCancelled)

    {

        // error!

        [self finishTransaction:transaction wasSuccessful:NO];

    }

    else

    {

        // this is fine, the user just cancelled, so don’t notify

        [[SKPaymentQueue defaultQueue] finishTransaction:transaction];

    }

}

#pragma mark –

#pragma mark SKPaymentTransactionObserver methods

//

// called when the transaction status is updated

//

– (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions

{

    for (SKPaymentTransaction *transaction in transactions)

    {

        switch (transaction.transactionState)

        {

            case SKPaymentTransactionStatePurchased:

                [self completeTransaction:transaction];

                break;

            case SKPaymentTransactionStateFailed:

                [self failedTransaction:transaction];

                break;

            case SKPaymentTransactionStateRestored:

                [self restoreTransaction:transaction];

                break;

            default:

                break;

        }

    }

}

@end