Twitter API for Cocoa developers

Overview

FHSTwitterEngine

Twitter API for Cocoa developers

Created by Nathaniel Symer

FHSTwitterEngine can:

  • Authenticate using OAuth and/or xAuth.
  • Make a request to just about every API endpoint.

Why you should use FHSTwitterEngine:

  • Single .h/.m pair
  • No dependencies
  • Shared instance
  • Scientific

This project started with OAuthConsumer.

Setup

CocoaPods

pod 'FHSTwitterEngine', '~> 2.0'

Manual

  1. Add FHSTwitterEngine.h and FHSTwitterEngine.m to your project
  • Link against SystemConfiguration.framework
  • Enable ARC for both files if applicable

Usage

Add import where necessary

#import "FHSTwitterEngine.h"

Set up FHSTwitterEngine

[[FHSTwitterEngine sharedEngine]permanentlySetConsumerKey:@"<consumer_key>" andSecret:@"<consumer_secret>"];

Or with a temporary consumer that gets cleared after each request

[[FHSTwitterEngine sharedEngine]temporarilySetConsumerKey:@"<consumer_key>" andSecret:@"<consumer_secret>"];

Set access token delegate (see header)

[[FHSTwitterEngine sharedEngine]setDelegate:myDelegate];

Login via OAuth:

UIViewController *loginController = [[FHSTwitterEngine sharedEngine]loginControllerWithCompletionHandler:^(BOOL success) {
    NSLog(success?@"L0L success":@"O noes!!! Loggen faylur!!!");
}];
[self presentViewController:loginController animated:YES completion:nil];

Login via XAuth:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
	@autoreleasepool {
		NSError *error = [[FHSTwitterEngine sharedEngine]getXAuthAccessTokenForUsername:@"<username>" password:@"<password>"];
    	// Handle error
    	dispatch_sync(dispatch_get_main_queue(), ^{
			@autoreleasepool {
    			// Update UI
    		}
   		});
	}
});

Clear the current consumer key

[[FHSTwitterEngine sharedEngine]clearConsumer];

Load a saved access_token (called when API calls are made):

[[FHSTwitterEngine sharedEngine]loadAccessToken];

Clear your access token:

[[FHSTwitterEngine sharedEngine]clearAccessToken];

Check if a session is valid:

[[FHSTwitterEngine sharedEngine]isAuthorized];

Do an API call (POST and GET):

dispatch_async((dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
	@autoreleasepool {
		id twitterData = [[FHSTwitterEngine sharedEngine]postTweet:@"Hi!"];
		// Handle twitterData (see "About GET Requests")
		dispatch_sync(dispatch_get_main_queue(), ^{
			@autoreleasepool {
    			// Update UI
    		}
   		});
	}
});

The "Singleton" Pattern

The singleton pattern allows the programmer to use the library across scopes without having to manually keep a reference to the FHSTwitterEngine object. When the app is killed, any memory used by FHSTwitterEngine is freed.

Threading

While you can use any threading technology for threading, I recommend Grand Central Dispatch (GCD).

General Comments

FHSTwitterEngine will attempt to preemptively detect errors in your requests, before they are actually sent. This includes missing parameters, and a lack of authorization. If FHSTwitterEngine detects that a user is not logged in, it will attempt to load an access token using its delegate. This process is designed to prevent bad requests from being needlessly sent.

About requests

Most methods return id. The returned object can be a(n):

  • NSMutableDictionary
  • NSMutableArray
  • UIImage
  • NSString
  • NSError
  • nil

Contact

Comments
  • Demo works only with provided consumer key and secret

    Demo works only with provided consumer key and secret

    When I changed consumer key and secret to my own FHSTwitterEngine stopped receiving user access token and secret on authorization.

    Strange thing but oAuth works (I mean receiving access token) only on device and doesn't on simulator. xAuth doesn't work anywhere,

    Please explain what is so special about consumer key and secret you provided. Can you give that Twitter app setup ?

    PS: Seems like my problem is exactly like this https://github.com/fhsjaagshs/FHSTwitterEngine/issues/7 with exactly the same error message.

    opened by MOOn2k 26
  • FHSTwitterEngine Not working in iOS 5.1

    FHSTwitterEngine Not working in iOS 5.1

    Hi, I had integrate this in my local application , its working fine with ios6.0 but while i had test in ios 5.1 its give error with copy pin, please do favor , how to resolve this

    opened by macIndian 17
  • Cocoapods support, changed project structure and added all pods requirements

    Cocoapods support, changed project structure and added all pods requirements

    Restructured the project to fit default cocoapods default structure for libraries.

    Kept the current example in sample folder.

    Moved source code to src directory

    Added project dependancies, license, and all necessary details to the podspec file

    opened by salah-ghanim 9
  • isAuthorized after relaunch

    isAuthorized after relaunch

    Please tell me,why after user authorize with reverse method "authenticateWithAccount:" and relaunch app, method "isAuthorize" return NO ??? But access token is present in user defaults.

    opened by rubikva 9
  • to post a tweet with current location

    to post a tweet with current location

    hey... m new bee in d dev..bt i need to knw how can we set current latitude and longitude location i.e. lat and long parameter in twitter api query....

    also,i wano ask hw can we get location id using FHSTwitterEngine...

    meanwhile every simple post i.e. with media and image is getting posted but .png image is not...i have read this issue but still m facing that prblm..dnt knw hw 2 solve...

    pls help me..

    opened by PreetySingh 9
  • FHSTwitterEngineController is hanging when the user doesnt have twitter installed on the device

    FHSTwitterEngineController is hanging when the user doesnt have twitter installed on the device

    The issue is in the below method in the FHSTwitterEngine.m line 1726

    • (void)showOAuthLoginControllerFromViewController:(UIViewController *)sender withCompletion:(void(^)(BOOL success, UIViewController *twitterEngineViewController))block { FHSTwitterEngineController *vc = [[FHSTwitterEngineController alloc]init]; UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:vc]; vc.modalTransitionStyle = UIModalTransitionStyleCoverVertical; objc_setAssociatedObject(vc, "FHSTwitterEngineOAuthCompletion", block, OBJC_ASSOCIATION_COPY_NONATOMIC); [sender presentViewController:navController animated:NO completion:nil]; }
    opened by cliftonmyers 8
  • Can't login on iPhone 6

    Can't login on iPhone 6

    I have a problem with login on iPhone 6. I'm using this code for display login view

    let loginController = FHSTwitterEngine.sharedEngine().loginControllerWithCompletionHandler { (Bool success) -> Void in } self.presentViewController(loginController, animated: true, completion: nil)

    but after few seconds screen automatically closing. Everything works fine on iPhone 6+.

    opened by voloshynslavik 8
  • Getting error FHSErrorDomain Code=204 whenever try to get tweets from my twitter profile.

    Getting error FHSErrorDomain Code=204 whenever try to get tweets from my twitter profile.

    Hey whenever i try to get tweets ,sometimes it is perfectly working and sometimes i am getting this error as shown below:

    Error Domain=FHSErrorDomain Code=204 "The request did not return any content." UserInfo=0xb287ec0 {NSLocalizedDescription=The request did not return any content.}

    This is my code to get tweets:

    NSArray *dict = [[FHSTwitterEngine sharedEngine]getHomeTimelineSinceID:[[FHSTwitterEngine sharedEngine]authenticatedID] count:30];

    Please help me.

    opened by rajat100919021 8
  • login via aAuth

    login via aAuth

    first i want to thank you for this great job but i have a problem on iOS 5 on the device when pressed on login via aAuth the FHSTwitterEngineController loading then nothing happend the view dismissed and return me to the main view that i called the FHSTwitterEngineController without login but on simulator it's work

    opened by Alkalouti 8
  • is -[FHSTwitterEngineController dealloc] missing a [super dealloc]

    is -[FHSTwitterEngineController dealloc] missing a [super dealloc]

    xcode 4.5.2 thinks so!

    best,

    /mtr

    ps: thanks for the nice package, i hope to be using it in an application that should be going into alpha soon!

    pps: yes, i did add all the -fno-obc-arc entries, otherwise, no compilation joy!

    opened by mrose17 8
  • I integrated this code and is working fine on simulator but not work on device iOS 8.1

    I integrated this code and is working fine on simulator but not work on device iOS 8.1

    I have integrated this code in my project. It was work fine with iOS 7.1 and also on simulator. but in device iOS 8.1 it can't open twitter login webview window. It shows on black screen. Please help me.

    opened by Mahesh-novaquad 6
  • Error code 204 -

    Error code 204 - "The request did not return any content."

    When I tried to fetch followers, Mostly time FHSTwitterEngine returns error like

    Error Domain=FHSErrorDomain Code=204 "The request did not return any content." UserInfo={NSLocalizedDescription=The request did not return any content.}

    Here is my code.. `- (void)getFollowersWithCursor:(NSString *)strCursor { NSString *username = [FHSTwitterEngine sharedEngine].authenticatedUsername; NSMutableDictionary * dict1 = [[FHSTwitterEngine sharedEngine] listFollowersForUser:username isID:NO withCursor:strCursor]; if ([dict1 isKindOfClass:[NSError class]]) { NSLog(@"%@", dict1); if(_arrFollowers.count > 0) { //Pass followers list to display on screen } else { [SVProgressHUD showErrorWithStatus:@"There was problem while fetching your followers."]; } } else { NSMutableArray *array=[dict1 objectForKey:@"users"]; if (array.count > 0) {

               //Do next steps as per my requirements
                if ([[dict1 objectForKey:@"next_cursor_str"] isEqualToString:@"0"]) {
                   //Pass followers list to display on screen
                 }
                else
                {
                    [self getFollowersWithCursor:[dict1 objectForKey:@"next_cursor_str"]];
                }
                
            }
        }
    

    }`

    Is there any solution which resolve this problem. I am currently run code on iOS 11.2 version Thanks in advance :)

    opened by AnjaliJariwala 0
  • FHSTwitterEngine trouble in ios 10.1.1

    FHSTwitterEngine trouble in ios 10.1.1

    when running FHSTwitterEngine in 9.0 version it generates Twitter savedHttpBody:oauth_token=2744544632-8W6wBwMEYhHRTHyeOm0OzOcFRtWHPEX6jRuhXbQ&oauth_token_secret=SbEkyNMoOMDATZiw7uHtt2FLsyzSgrsPsv21VBGjmKsi7&user_id=2744544632&screen_name=kapilcdn&x_auth_expires=0 Twitter Access token:<FHSToken: 0x15979a90>

    but when running in ios 10.1.1 Twitter savedHttpBody:(null) Twitter Access token:<FHSToken: 0x170821f40>

    it is unable to give savedHttpBody


    it gives (NSError) NSError = domain: @"NSURLErrorDomain" - code: 18446744073709550604{ _userInfo = 0x0000000170464700 3 key/value pairs }

    bug 
    opened by khushboom 3
  • postTweet: returning the wrong error for {code: 187, message:

    postTweet: returning the wrong error for {code: 187, message: "Status is a duplicate."}

    Code: NSError *twitterError = [[FHSTwitterEngine sharedEngine] postTweet:tweetStr];

    Error: Error Domain=FHSErrorDomain Code=204 "The request did not return any content." UserInfo={NSLocalizedDescription=The request did not return any content.}

    Looked into the data variable in - (id)sendRequest:(NSURLRequest *)request and found that actual error was {"errors":[{"code":187,"message":"Status is a duplicate."}]}

    bug 
    opened by ankurp-munchado 3
  • Remove user in list!

    Remove user in list!

    Most of the time does not work and this error happens:

    Error Domain=NSURLErrorDomain Code=-1012 "(null)" UserInfo={NSErrorFailingURLKey=https://api.twitter.com/1.1/lists/members/destroy_all.json,NSErrorFailingURLStringKey=https://api.twitter.com/1.1/lists/members/destroy_all.json, NSUnderlyingError=0x178d8a60 {Error Domain=kCFErrorDomainCFNetwork Code=-1012 "(null)" UserInfo={_kCFURLErrorAuthFailedResponseKey=<CFURLResponse 0x17a32f20 [0x3b6a1a00]>{url = https://api.twitter.com/1.1/lists/members/destroy_all.json}}}}

    Using this code: FHSTwitterEngine.sharedEngine().removeUsersFromListWithID(listTwitterId.stringValue.lowercaseString, users: twitter)

    opened by Thuran 2
  • Support for videos

    Support for videos

    • https://about.twitter.com/videos-on-twitter
    • https://blog.twitter.com/2015/now-on-twitter-group-direct-messages-and-mobile-video-capture
    • https://twittercommunity.com/t/twitter-video-support-in-rest-and-streaming-api/31258
    • https://blog.twitter.com/2015/rest-api-now-supports-native-video-upload
    opened by dkhamsing 2
Owner
Nathaniel Symer
Reverse engineering reality.
Nathaniel Symer
The Easiest and Simplest iOS library for Twitter and Facebook. Just Drop in and Use!

EasySocial iOS Library for Twitter and Facebook This library allows your apps to use Twitter and Facebook with minimal understanding of the relevant S

pj 124 Nov 17, 2022
A Twitter framework for iOS & OS X written in Swift

Getting Started Installation If you're using Xcode 6 and above, Swifter can be installed by simply dragging the Swifter Xcode project into your own pr

Matt Donnelly 2.4k Dec 30, 2022
Twitter Clone for iOS With Swift

Postwitter Date: December 1, 2021 Product Name: Postwitter Problem Statement: iO

Shohin Abdulkhamidov 3 Aug 16, 2022
Giphy API client for iOS in Objective-C

Giphy-iOS Giphy-iOS is a Giphy API client for iOS in Objective-C. Usage To run the example project, clone the repo, and run pod install from the Examp

alex choi 52 Jul 11, 2019
An easy-to-use Objective-C wrapper for the Uber API (no longer supported)

UberKit UberKit is a simple Objective-C wrapper for the new Uber API . Installation Cocoapods UberKit is available through Cocoapods. To install it, s

Sachin Kesiraju 95 Jun 30, 2022
Unofficial Dribbble iOS wrapper allows you to integrate Dribble API into iOS application (Designer, Shot, Comment, User Story, Like, Follow)

DribbbleSDK DribbbleSDK is easy-to-use iOS wrapper for Dribbble SDK. We're working hard to complete the full coverage of available methods and make th

Agilie Team 74 Dec 2, 2020
ObjectiveFlickr, a Flickr API framework for Objective-C

ObjectiveFlickr ObjectiveFlickr is a Flickr API framework designed for Mac and iPhone apps. OAuth Support ObjectiveFlickr now supports Flickr's new OA

Lukhnos Liu 714 Jan 9, 2023
A Swift wrapper for Foursquare API. iOS and OSX.

Das Quadrat Das Quadrat is Foursquare API wrapper written in Swift. Features Supports iOS and OSX. Covers all API endpoints. Authorization process imp

Constantine Fry 171 Jun 18, 2022
Unofficial GitHub API client in Swift

Github.swift ❤️ Support my apps ❤️ Push Hero - pure Swift native macOS application to test push notifications PastePal - Pasteboard, note and shortcut

Khoa 184 Nov 25, 2022
Unified API Library for: Cloud Storage, Social Log-In, Social Interaction, Payment, Email, SMS, POIs, Video & Messaging.

Unified API Library for: Cloud Storage, Social Log-In, Social Interaction, Payment, Email, SMS, POIs, Video & Messaging. Included services are Dropbox, Google Drive, OneDrive, OneDrive for Business, Box, Egnyte, PayPal, Stripe, Google Places, Foursquare, Yelp, YouTube, Vimeo, Twitch, Facebook Messenger, Telegram, Line, Viber, Facebook, GitHub, Google+, LinkedIn, Slack, Twitter, Windows Live, Yahoo, Mailjet, Sendgrid, Twilio, Nexmo, Twizo.

CloudRail 195 Nov 29, 2021
A swift SDK for Medium's OAuth2 API

Medium SDK - Swift A library to allow access to Medium API for any Swift iOS application. Features Medium.com authorization & token handling Login sta

null 11 Jan 22, 2022
An Elegant Spotify Web API Library Written in Swift for iOS and macOS

Written in Swift 4.2 Spartan is a lightweight, elegant, and easy to use Spotify Web API wrapper library for iOS and macOS written in Swift 3. Under th

Dalton Hinterscher 107 Nov 8, 2022
Swift Wrapper For Bittrex API

BittrexApiKit Swift client for Bittrex api. It support all APIs with most recent changes. more info here let api = Bittrex(apikey: "api key", secretke

Saeid 8 Apr 5, 2021
Easy and powerful way to interact with VK API for iOS and macOS

Easy and powerful way to interact with VK API for iOS and macOS. Key features ?? It's not ios-vk-sdk ?? ?? One library for iOS and mac OS ?? ?? Fully

null 260 Dec 22, 2022
Instagram API client written in Swift

SwiftInstagram is a wrapper for the Instagram API written in Swift. It allows you to authenticate users and request data from Instagram effortlessly.

Ander Goig 579 Dec 31, 2022
A Slack API Client for the Perfect Server-Side Swift Framework

PerfectSlackAPIClient is an API Client to access the Slack API from your Perfect Server Side Swift application. It is build on top of PerfectAPIClient

Cap.雪ノ下八幡 2 Dec 1, 2019
An API wrapper for bitFlyer.

SwiftFlyer An API wrapper for bitFlyer that supports all providing API. API Document https://lightning.bitflyer.jp/docs Usage Public API Fetch a marke

Ryo Ishikawa 39 Nov 3, 2022
A Swift library for the Forecast.io Dark Sky API

Requirements To use ForecastIO, all you need is an API key for the Dark Sky API. ForecastIO supports iOS (≥9.0), macOS (≥10.10), watchOS (≥2.0), and t

Satyam Ghodasara 163 Jul 26, 2022
A clima based app with use of API

Clima Our Goal It’s time to take our app development skills to the next level. We’re going to introduce you to the wonderful world of Application Prog

null 0 Nov 28, 2021