The Easiest and Simplest iOS library for Twitter and Facebook. Just Drop in and Use!
This library allows your apps to use Twitter and Facebook with minimal understanding of the relevant SDK. It is super easy to use and elegantly designed. It will save you time.
Many other libraries are overly complicated and offer functionality that you do not need in your app. The included Example Project demonstrates most of the features offered.
EasySocial does only these things:
pod 'EasySocial', '~> 1.0'
Social.frameworkto your project
Accounts.frameworkto your project
EasySocialfolder into your project (Ensure you check
Copy items into destination group's folder)
-Prefix.pchfile in the
Supporting FilesFolder within XCode. For XCode 6, you will need to create a
pchfile from scratch.
//Now you do not need to include those headers anywhere else in your project. #import "EasyFacebook.h" #import "EasyTwitter.h"
FacebookSDK.frameworkinto your project.
Bundle IDyou give your app on XCode matches what you register with Facebook
"Single Sign On"in Facebook
-Info.plistfile by inserting
FacebookAppID,
FacebookDisplayNameand
URL typeskeys
Developeraccount. That way you can test your app while you are developing it. In production, Facebook must approve your app to use some features
AppDelegate.mfile, include:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation { BOOL wasHandled1 = [EasyFacebook handleOpenURL:url sourceApplication:sourceApplication]; // BOOL wasHandled2 = [GPPURLHandler handleURL:url sourceApplication:sourceApplication annotation:annotation]; // BOOL wasHandled3 = [TumblrAPI handleURL:url];return wasHandled1;
// return (wasHandled1 || wasHandled2 || wasHandled3);
}
Before you can use EasyTwitter, you must instantiate the
EasyTwitterclass.
+ (EasyTwitter *)sharedEasyTwitterClient
The class is a singleton class meaning only one is ever created. In practice, the class is automatically instantiated without any action on your part. You can use the class by typing:
[EasyTwitter sharedEasyTwitterClient].XXXor
[[EasyTwitter sharedEasyTwitterClient] XXX].
Before your app can use Twitter, the user must grant permission to your app.
- (void)requestPermissionForAppToUseTwitterSuccess:(void(^)(BOOL granted, BOOL accountsFound, NSArray *accounts))success failure:(void(^)(NSError *error))failure
BOOL grantedwill indicate if the user granted permission. If the user does not grant permission, they must go to the iOS built-in
SettingsApp ->
Privacy->
BOOL accountsFoundwill indicate if any system-stored Twitter Accounts were found (provided
granted==YES). If none were found, remind the user to save their Twitter credentials in
SettingsApp ->
NSArray *accountswill contain
ACAccountobjects. These represent the Twitter accounts found. You can search through all the
ACAccountobjects to select the desired Twitter account to send tweets from.
ACAccountcontains two properties that are useful:
Once you discover the required account, set it.
//In practice, set it to the required account. This is the default setting automatically set. [EasyTwitter sharedEasyTwitterClient].account = [accounts firstObject];
A Tweet is a (max) 140 character
messagethat is propagated to other Twitter users via the Twittersphere. URL links can be embedded in the
message.They are automatically detected and minified to save characters. Images can also be attached. All images are uploaded to Twitter's servers.
//Plain Tweet - (void)sendTweetWithMessage:(NSString *) message twitterResponse:(void(^)(id responseJSON, NSDictionary *JSONError, NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error))response failure:(void(^)(EasyTwitterIssues issue))failure //Tweet with an image in *NSData format - (void)sendTweetWithMessage:(NSString *) message image:(NSData *) image mimeType:(NSString *) mimeType requestShowLoadScreen:(BOOL) show twitterResponse:(void(^)(id responseJSON, NSDictionary *JSONError, NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error))response failure:(void(^)(EasyTwitterIssues issue))failure //Tweet with an image referred to by a URL - (void)sendTweetWithMessage:(NSString *) message imageURL:(NSURL *) imageURL twitterResponse:(void(^)(id responseJSON, NSDictionary *JSONError, NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error))response failure:(void(^)(EasyTwitterIssues issue))failure
(NSString *) messageis the message to tweet.
(NSData *) imagerefers to an image. If you have a
UIImageobject, it must be converted to a
NSDataobject by using
UIImageJPEGRepresentation()or
UIImagePNGRepresentation().
(NSString *) mimeTyperefers to the Mime Type of the image. It should be one of
image/png,
image/jpeg,or
image/gif.If unspecified,
image/pngwill be assumed.
(NSURL *) imageURLrefers to the URL address of the image file. It's Mime Type will be guessed by the file's extension.
(BOOL) showis a private argument. Always set it to
YES.
NSDictionary *JSONErroris part of the response back from Twitter's REST API. If
JSONError == nil,the tweet was posted successfully. If it is not
nil,there was an issue.
The issue can be determined by reading the error code and error message.
//pseudo code int errorCode = [[JSONError objectForKey:@"code"] intValue]; //JSON error code as opposed to HTTP error code NSString *errorMessage = [JSONError objectForKey:@"message"];
EasyTwitterIssues issueis returned by the
failureblock. It represents an error before Twitter's REST API is even called.
If
issue == EasyTwitterNoAccountSet,it means that you attempted to send a tweet without setting a Twitter account.
A user's
home-timelinerepresents the most recent tweets and retweets. It should be noted that the
home-timelineis different from the
user-timeline.
- (void)loadTimelineWithCount:(int) count completion:(void (^)(NSArray *data, NSError *error))completion
(int) countrefers to how many recent items from the home-timeline you want returned. The maximum is 200.
NSArray *datawill contain
NSDictionaryobjects which represent an item from the timeline. The most recent item is at
index==0.During development, you can observe the contents of each item using:
NSLog(@"data: %@", data)
Finally you can extract the desired data like this:
//pseudo code cell.textLabel.text = [data[row] objectForKey:@"text"]; //Main contents of item cell.detailTextLabel.text = [[data[row] objectForKey:@"user"] objectForKey:@"""screen_name"""]; //Screen name of owner of item
EasyTwitterPermissionGrantedNotification- Posted when the user grants permission to access system-stored Twitter accounts. It does not imply that any twitter accounts were found.
EasyTwitterAccountSetNotification- Posted when you set an
ACAccountobject as the Twitter account to tweet from. This notification is also posted when the default Twitter account is set automatically (without any action on your part).
EasyTwitterTweetSentNotification- Posted when a tweet was successfully sent. It is usually more useful to monitor the
NSDictionary *JSONErrorargument in the
responsecallback block of the
sendTweetWithMessage:methods. A
nilerror response indicates a successful tweet.
Both methods prescribed in the protocol are
optional.You will have to set the
delegateproperty appropriately to subscribe to the protocol. It may be useful to implement them as demonstrated in the accompanying
Example Project.
showLoadingScreen:is called before a potentially time-consuming activity begins.
hideLoadingScreen:is called after a time-consuming activity finishes.
It is expected that you show the user that background activity is occurring via a UI element.
The delegate methods are called before and after:
requestPermissionForAppToUseTwitterSuccess:failure:
sendTweetWithMessage:image:mimeType:requestShowLoadScreen:twitterResponse:failure:
sendTweetWithMessage:imageURL:twitterResponse:failure:
sendTweetWithMessage:twitterResponse:failure:
loadTimelineWithCount:completion:
Before you can use EasyFacebook, you must instantiate the
EasyFacebookclass.
+ (EasyFacebook *)sharedEasyFacebookClient
The class is a singleton class meaning only one is ever created. In practice, the class is automatically instantiated without any action on your part. You can use the class by typing:
[EasyFacebook sharedEasyFacebookClient].XXXor
[[EasyFacebook sharedEasyFacebookClient] XXX].
Before you can interact with the FacebookSDK, you must have a logged in user.
- (void)openSession //For logging in - (void)closeSession //For logging out - (BOOL)isLoggedIn //For checking logged in status
By calling the
openSessionmethod, the user will undergo the standard logging in process. This usually involves opening up the official Facebook app (if installed). Otherwise Safari browser will be opened instead. The user will be asked to grant permission to your app to access their details. Once approved, any future calls to
openSessionwill briefly open up the Facebook app but will almost immediately transfer back to your app - since the user had already granted approval in the past (provided the approval is not later revoked).
The
closeSessionmethod will immediately log out the user.
The
(BOOL)isLoggedInmethod will return whether the user is currently logged in or out.
If the user logs in and later exits your app, a cached token will usually be saved locally. When your app is opened again, the user will usually not have to log in again. This is part of the Auto-Log In feature.
For security reasons, if you want to turn off Auto-Log In behaviour, you can listen to UIApplicationWillTerminateNotification and call
closeSessionto log out the user.
When the user is being logged in, the FacebookSDK requires the initial permissions requested. The default permissions are:
If you want to modify the permissions requested, before calling
openSessionyou can set
readPermissions:
//Set the readPermissions to what ever you want [EasyFacebook sharedEasyFacebookClient].readPermissions = @[@"public_profile", @"email", @"user_friends"];
Read the
Notificationssection below if you want to what know state changes are available to you.
After the user logs in, a call to fetch the user's basic information is automatically done. However, if you want the latest information on demand then call this method.
- (void)fetchUserInformation
Once the information arrives, the
EasyFacebookUserInfoFetchedNotificationnotification is posted. Once posted, you can extract the latest details using these properties:
@property NSString *UserEmail- Only available if
@property NSString *UserFirstName
@property NSString *UserGender
@property NSString *UserObjectID- usually referred to as
id(unique to the user - store in databases)
@property NSString *UserLastName
@property NSString *UserLink
@property NSString *UserLocale
@property NSString *UserName
@property NSString *UserTimeZone
@property NSString *UserVerified
Publishing to the timeline requires the
publish_actionspermission. You will also require Facebook approval once your app is ready to go to production.
- (BOOL)isPublishPermissionsAvailableQuickCheck - (void)isPublishPermissionsAvailableFullCheck:(void(^)(BOOL result, NSError *error))responseHandler - (void)requestPublishPermissions:(void(^)(BOOL granted, NSError *error))responseHandler
(BOOL)isPublishPermissionsAvailableQuickCheckchecks if
publish_actionspermission is granted to the current
access token.It is 99% accurate since the permissions granted could have changed since the
access tokenwas issued. The permissions could also be changed by the user via the Facebook website external to your app. The method will immediately return however since it does not make any REST API calls.
(void)isPublishPermissionsAvailableFullCheckwill perform a 100% accurate check for
publish_actionspermission. It will make a REST API call and will return with a
BOOL resultresponse. If
result==YES,then publishing permission is available.
If publishing permission is not available, you will have to request it by calling
(void)requestPublishPermissionsmethod. A response where
granted==YESwill indicate that the user has granted permission.
publish_actionspermission is required. By calling the
publishStoryWithParams:completion:method below, it automatically also calls the
requestPublishPermissions:method.
- (void)publishStoryWithParams:(NSDictionary *)params completion:(void(^)(BOOL success, NSError *error))completion
(NSDictionary *)paramscan have these parameters:
BOOL successwill be the response in the
completionblock. If
success==YES,the share post was successful.
As an example:
NSDictionary *params = @{@"link" : @"http://www.google.com", @"name" : @"Google", @"caption" : @"#1 search engine", @"picture" : @"https://www.google.com/images/srpr/logo11w.png", @"description" : @"Home page Logo", @"message" : @"hello" };
The output will be:
EasyFacebookLoggedInNotification- Posted when the user successfully logs in. The notification is also posted after an auto-log in.
EasyFacebookLoggedOutNotification- Posted when the user logs out intentionally or due to unexpected reasons.
EasyFacebookUserInfoFetchedNotification- Posted when the user's basic information becomes available. This will happen automatically shortly after the user logs in, or after
fetchUserInformationmethod is explicitly called. See above for information on what basic information is available.
EasyFacebookUserCancelledLoginNotification- Posted when the user is given the opportunity to log in but decides to cancel the process. The user is usually taken outside the app to the official Facebook app to log in. If the app is not installed, Safari browser is opened with the log in dialog shown via a website.
EasyFacebookPublishPermissionGrantedNotification- Posted when the user grants permission for the app to publish on their timeline.
EasyFacebookPublishPermissionDeclinedNotification- Posted when the user declines to grant permission for the app to publish on their timeline.
EasyFacebookStoryPublishedNotification- Posted when the share attempt is successfully published on the user's timeline.
Both methods prescribed in the protocol are
optional.You will have to set the
delegateproperty appropriately to subscribe to the protocol. It may be useful to implement them as demonstrated in the accompanying
Example Project.
showLoadingScreen:is called before a potentially time-consuming activity begins.
hideLoadingScreen:is called after a time-consuming activity finishes.
It is expected that you show the user that background activity is occurring via a UI element.
The delegate methods are called before and after:
publishStoryWithParams:completion:
@property BOOL preventAppShutDown- iOS 8 incorporates a different Memory Management Policy. If you find that your app is getting shut down by iOS after the user is taken to the Facebook app as part of the log in process, then set this property to
YES.
@property BOOL facebookLoggingBehaviourOn- For diagnostic purposes, if you want the FacebookSDK to log full details (in the debug window) on what it is doing behind the scenes, then set this property to
YES.
If you found this library useful, please Star it on github. Feel free to fork or provide pull requests. Any bug reports will be warmly received.