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

Advertisements

Leave a Reply

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

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s