Friday 30 January 2015

Silent Text and Image Sharing on Facebook and Twitter using single sign

Steps To added silent Sharing in your iOS project

Step #1: First you have add social and account Framework in your project
Step #2: Import account and social framework in you class like #import <Accounts/Accounts.h> & #import <Social/Social.h>
Step #3Add your AppId and Twitter Consumer & Secret Key in defines
Step #4For Facebook & Twitter Sharing copy paste the available method define in ShareViewController.h below
Step #5: Register notification ACAccountStoreDidChangeNotification to receive call if user change their account from setting



ShareViewController.h 
#import <Accounts/Accounts.h>
#import <Social/Social.h>

#define kTwitterConsumerKey @"" // add your Twitter ConsumerKey
#define kTwitterSecret @"" // add your Twitter Secret
#define kFaceBookAppId @"" // add your app Facebook AppId



@interface ShareViewController ()
{
    
}
@property(nonatomic,strong) ACAccountStore *accountStore;
@property(nonatomic,strong)ACAccount *facebookAccount;
@property(nonatomic,strong)ACAccount *twitterAccount;

-(void)postOnFacebookWithText:(NSString*)sharingText; 
// For Text sharing only on Facebook 

-(void)postOnFacebookWithText:(NSString*)sharingText  
                    withImage:(UIImage*)image;
// For Text and Image  sharing only on Facebook

-(void)postToTwitterWithText:(NSString*)TwitterSharing
                 withPhotoId:(NSString*)mediaId; 
// For Text sharing only on Twitter pass mediaId to nil

-(void)postToTwitterDeprecatedAPIWithText:(NSString*)TwitterSharing
                                withImage:(UIImage*)image; 
// For Text and Image sharing only on Twitter using Deprecated

-(void)postToTwitterWithText:(NSString*)TwitterSharing
                   withImage:(UIImage*)image; 
// For Text and Image sharing on Twitter


@end


ShareViewController.m

@implementation ShareViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(accountChanged:) name:ACAccountStoreDidChangeNotification object:nil];

  
//e.g.

    UIImage *image=[UIImage imageNamed:@"imgres.jpg"];
    NSString *sharingText=@"This is shaing text for app";
    
  //  [self postOnFacebookWIthText:sharingText]; //Shaing on facebook only text
  //  [self postOnFacebookWIthText:sharingText withImage:image];   //Shaing on facebook text and Image
  //  [self postToTwitterWithText:sharingText withPhotoId:nil]; //Shaing on Twitter only text
  //  [self postToTwitterDeprecatedAPIWithText:sharingText withImage:image]; //Shaing on Twitter text and Image with DeprecatedAPI
   // [self postToTwitterWithText:sharingText withImage:image]; //Shaing on Twitter text and Image

}

#pragma mark Facebook Sharing with account Framework
-(void)postOnFacebookWithText:(NSString*)sharingText{
    
    if (!_accountStore)
        _accountStore = [[ACAccountStore alloc] init];
    
        ACAccountType *facebookAccountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
        // Specify App ID and permissions
         NSDictionary *options2 = @{
                                    ACFacebookAppIdKey: kFaceBookAppId,
                                    ACFacebookPermissionsKey: @[@"publish_actions"],
                                    ACFacebookAudienceKey: ACFacebookAudienceFriends
                                    };
         [_accountStore requestAccessToAccountsWithType:facebookAccountType options:options2 completion:^(BOOL granted, NSError *error) {
             if (granted) {
                 NSArray *accounts = [_accountStore accountsWithAccountType:facebookAccountType];
                 if ([accounts count] > 0){

                     _facebookAccount = [accounts lastObject];
                     NSDictionary *parameters = @{@"message":sharingText};
                     NSURL *feedURL = [NSURL URLWithString:@"https://graph.facebook.com/me/feed"]; //for text sharing
                     
                     SLRequest *feedRequest = [SLRequest
                                               requestForServiceType:SLServiceTypeFacebook
                                               requestMethod:SLRequestMethodPOST
                                               URL:feedURL
                                               parameters:parameters];
                     [feedRequest setAccount:_facebookAccount];
                     
                     [feedRequest performRequestWithHandler:^(NSData *responseData,
                                                              NSHTTPURLResponse *urlResponse, NSError *error)
                      {
                          // Handle response
                          NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
                          NSLog(@"Response: %@", response);
                          
                          if (response[@"id"]) {
                              
                              NSLog(@" %@", @"Shared Successfullly");
                          }
                          else{
                              
                              NSLog(@"Error: %@", [error description]);
                          }
                      }];
                 }
                 else{
                     
                     NSLog(@"Error: %@", @"Please configure your Facebook account in setting");
                 }
             }
             else {
                 NSLog(@"Access denied 2");
                 NSLog(@"%@", [error description]);
             }
         }];
}

-(void)postOnFacebookWithText:(NSString*)sharingText
                    withImage:(UIImage*)image{
    
    if (!_accountStore)
        _accountStore = [[ACAccountStore alloc] init];
    
    ACAccountType *facebookAccountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
    // Specify App ID and permissions
     NSDictionary *options2 = @{
                                ACFacebookAppIdKey: kFaceBookAppId,
                                ACFacebookPermissionsKey: @[@"publish_actions"],
                                ACFacebookAudienceKey: ACFacebookAudienceFriends
                                };
     [_accountStore requestAccessToAccountsWithType:facebookAccountType options:options2 completion:^(BOOL granted, NSError *error) {
         if (granted) {
             
             NSArray *accounts = [_accountStore accountsWithAccountType:facebookAccountType];
             
             if ([accounts count] > 0){
                 
                 _facebookAccount = [accounts lastObject];
                 NSDictionary *parameters = @{@"message":sharingText};
                 NSURL *feedURL = [NSURL URLWithString:@"https://graph.facebook.com/me/photos"]; //for photo & Text Sharing shaing
                     
                 SLRequest *feedRequest = [SLRequest
                                           requestForServiceType:SLServiceTypeFacebook
                                           requestMethod:SLRequestMethodPOST
                                           URL:feedURL
                                           parameters:parameters];
                 [feedRequest setAccount:_facebookAccount];
                 
                 UIImage *image=[UIImage imageNamed:@"imgres.jpg"];
                 [feedRequest addMultipartData:UIImageJPEGRepresentation(image, 0.9) withName:@"imgres" type:@"application/octet-stream" filename:@"imgres.jpg"];
                 
                 [feedRequest performRequestWithHandler:^(NSData *responseData,
                                                          NSHTTPURLResponse *urlResponse, NSError *error)
                  {
                      // Handle response
                      NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
                      NSLog(@"Response: %@", response);

                      if (response[@"id"]) {
                          
                          NSLog(@" %@", @"Shared Successfullly");
                      }
                      else{
                          
                          NSLog(@"Error: %@", [error description]);
                      }
                  }];
             }
             else{
             
                 NSLog(@"Error: %@", @"Please configure your Facebook account in setting");
             }
         }
         else {
             NSLog(@"Access denied 2");
             NSLog(@"%@", [error description]);
         }
     }];
}


#pragma mark Twitter Sharing with account Framework
// Using statuses/update.json
-(void)postToTwitterWithText:(NSString*)TwitterSharing
                 withPhotoId:(NSString*)mediaId{
    
    if (!_accountStore)
        _accountStore = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [_accountStore accountTypeWithAccountTypeIdentifier:
                                  ACAccountTypeIdentifierTwitter];
    
    
    //    NSDictionary *options2 = @{
    //                               @"oauth_consumerkey": kTwitterConsumerKey,
    //                               @"oauth_Secretkey": kTwitterSecret
    //                               };
    
    [_accountStore requestAccessToAccountsWithType:accountType options:nil
                                  completion:^(BOOL granted, NSError *error)
     {
         if (granted){
             
             NSArray *arrayOfAccounts = [_accountStore accountsWithAccountType:accountType];
             if ([arrayOfAccounts count] > 0){
                 
                 _twitterAccount = [arrayOfAccounts lastObject];
                 NSDictionary *message = @{@"status":TwitterSharing};
                 if ([mediaId length]>0) // media Id exit
                     message = @{@"status":TwitterSharing,@"media_ids":@[mediaId]};
                 
                 NSURL *requestURL = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/update.json"]; // for txt sharing
                 
                 SLRequest *postRequest = [SLRequest
                                           requestForServiceType:SLServiceTypeTwitter
                                           requestMethod:SLRequestMethodPOST
                                           URL:requestURL parameters:message];
                 [postRequest setAccount:_twitterAccount];
                 
                 // Block handler to manage the response
                 [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error){
                     
                     NSDictionary *responseDic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:nil];
                     NSLog(@"%@",responseDic);
                     if ([urlResponse statusCode]==200) {

                         NSLog(@"Shared Succesffull");
                     }
                     else{
                         
                         NSArray *errorArray=responseDic[@"errors"];
                         if ([errorArray count]) {
                             NSDictionary *errorDic=[errorArray lastObject];
                             NSString *message=[errorDic objectForKey:@"message"];
                             NSLog(@"Twitter response, Error Message: %@",message);
                         }
                     }
                 }];
             }
             else{
                 NSLog(@"Error: %@", @"Please configure your twitter account in setting");
             }
         }
         else {
             NSLog(@"Error: %@", [error description]);
             NSLog(@"Access denied");
         }
     }];
}

/* POST statuses/update_with_media (deprecated)*/
-(void)postToTwitterDeprecatedAPIWithText:(NSString*)TwitterSharing
                                withImage:(UIImage*)image{
    
    if (!_accountStore)
        _accountStore = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [_accountStore accountTypeWithAccountTypeIdentifier:
                                  ACAccountTypeIdentifierTwitter];
    
    [_accountStore requestAccessToAccountsWithType:accountType options:nil
                                  completion:^(BOOL granted, NSError *error){
                                      
         if (granted){
             
             NSArray *arrayOfAccounts = [_accountStore accountsWithAccountType:accountType];
            if ([arrayOfAccounts count] > 0){
                 
                _twitterAccount = [arrayOfAccounts lastObject];
                NSDictionary *message = @{@"status": TwitterSharing};
                NSURL *requestURL = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/update_with_media.json"]; // for image and text sharing
                SLRequest *postRequest = [SLRequest
                                           requestForServiceType:SLServiceTypeTwitter
                                           requestMethod:SLRequestMethodPOST
                                           URL:requestURL parameters:message];
                [postRequest setAccount:_twitterAccount];
                [postRequest addMultipartData:UIImageJPEGRepresentation(image, 0.9) withName:@"media" type:@"image/jpeg" filename:@"imgres.jpg"];
                
                     // Block handler to manage the response
                     [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error){
                         
                         NSDictionary *responseDic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:nil];
                         NSLog(@"%@",responseDic);
                         if ([urlResponse statusCode]==200) {
                             
                             NSLog(@"Shared Succesffull");
                             
                         }
                         else{
                             
                             NSArray *errorArray=responseDic[@"errors"];
                             if ([errorArray count]) {
                                 NSDictionary *errorDic=[errorArray lastObject];
                                 NSString *message=[errorDic objectForKey:@"message"];
                                 NSLog(@"Twitter response, Error Message: %@",message);
                             }
                             
                         }
                      }];
             }
            else{
                NSLog(@"Error: %@", @"Please configure your twitter account in setting");
            }
         }
         else {
             
             NSLog(@"Error: %@", [error description]);
             NSLog(@"Access denied");
         }
     }];
}


// Using /media/upload.json and statuses/update.json API
-(void)postToTwitterWithText:(NSString*)TwitterSharing
                   withImage:(UIImage*)image{
    
    if (!_accountStore)
        _accountStore = [[ACAccountStore alloc] init];
    ACAccountType *accountType = [_accountStore accountTypeWithAccountTypeIdentifier:
                                  ACAccountTypeIdentifierTwitter];
    
    [_accountStore requestAccessToAccountsWithType:accountType options:nil
                                  completion:^(BOOL granted, NSError *error){
                                      
         if (granted){
             NSArray *arrayOfAccounts = [_accountStore accountsWithAccountType:accountType];
             if ([arrayOfAccounts count] > 0){
                 
                  _twitterAccount = [arrayOfAccounts lastObject];
                 NSDictionary *message = @{@"status": TwitterSharing};
                 NSURL *requestURL = [NSURL URLWithString:@"https://upload.twitter.com/1.1/media/upload.json"]; // for image uploading
                 
                 SLRequest *postRequest = [SLRequest
                                           requestForServiceType:SLServiceTypeTwitter
                                           requestMethod:SLRequestMethodPOST
                                           URL:requestURL parameters:message];
                 [postRequest setAccount:_twitterAccount];
                 UIImage *image=[UIImage imageNamed:@"imgres.jpg"];
                 [postRequest addMultipartData:UIImageJPEGRepresentation(image, 0.9) withName:@"media" type:@"image/jpeg" filename:@"imgres.jpg"];
                 
                 
                 // Block handler to manage the response
                 [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error){
                     
                     
                     NSDictionary *responseDic=[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:nil];
                     NSLog(@"%@",responseDic);
                     if ([urlResponse statusCode]==200) {
                         
                         NSLog(@"Upload Succesffull");
                         NSString *mediaId=[[responseDic objectForKey:@"media_id"] stringValue];
                         [self postToTwitterWithText:TwitterSharing withPhotoId:mediaId];

                     }
                     else{
                         
                         NSArray *errorArray=responseDic[@"errors"];
                         if ([errorArray count]) {
                             NSDictionary *errorDic=[errorArray lastObject];
                             NSString *message=[errorDic objectForKey:@"message"];
                             NSLog(@"Twitter response, Error Message: %@",message);
                         }
                     }
                  }];
             }
             else{
                 NSLog(@"Error: %@", @"Please configure your twitter account in setting");
             }
         }
         else {
             
             NSLog(@"Error: %@", [error description]);
             NSLog(@"Access denied");
         }
     }];
}



#pragma mark Account Change notification
-(void)accountChanged:(NSNotification *)notification{
    
    // Facebook
    [self.accountStore renewCredentialsForAccount:(ACAccount *)self.facebookAccount completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){
        if(!error)
        {
            switch (renewResult) {
                case ACAccountCredentialRenewResultRenewed:
                    NSLog(@"Good to go");
                    break;
                case ACAccountCredentialRenewResultRejected:
                    NSLog(@"User declined permission");
                    break;
                case ACAccountCredentialRenewResultFailed:
                    NSLog(@"non-user-initiated cancel, you may attempt to retry");
                    break;
                default:
                    break;
            }
        }
        else{
            //handle error gracefully
            NSLog(@"error from renew credentials%@",error);
        }
    }];
    
    // Twitter
    [self.accountStore renewCredentialsForAccount:(ACAccount *)self.twitterAccount completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){
        if(!error)
        {
            switch (renewResult) {
                case ACAccountCredentialRenewResultRenewed:
                    NSLog(@"Good to go");
                    break;
                case ACAccountCredentialRenewResultRejected:
                    NSLog(@"User declined permission");
                    break;
                case ACAccountCredentialRenewResultFailed:
                    NSLog(@"non-user-initiated cancel, you may attempt to retry");
                    break;
                default:
                    break;
            }
        }
        else{
            //handle error gracefully
            NSLog(@"error from renew credentials%@",error);
        }
    }];
}


@end

#Xcode #iOS #Sharing #Coding #iPhone #Social #Facebook #Twitter
© 2015 Girijesh
In case if any query/Concern send me a email @girijeshkumar2007@gmail.com

Thanks,

No comments: