How to integrate Twitter support into an iOS application? - xcode

How to integrate Twitter support into an iOS application?

Stefan Arentz's Twitter library is a pleasure to use - it contains the views you need, there is basically no coding to do. Do register your app early with twitter and get a submission to request xAuth authentication permission so that you do not have to use the clumsy web-based oAuth method. With xAuth it is as simple as submitting username and password and keeping the returned authentication token to submit a tweet.

Here is an example:
Call -(void)sendTweet from your IBAction.
// Sending tweets from within the application
-(void)sendTweet {
// check if device capable of sending tweets
if([TWTweetComposeViewControllercanSendTweet])
{
TWTweetComposeViewController *tweetSheet = [[TWTweetComposeViewControlleralloc] init];
[tweetSheet setInitialText:#"Twitting from my iSecret App"];
self.imageString = #"theSecret.png";
if(self.imageString) {
[tweetSheet addImage:[UIImageimageNamed:self.imageString]];
}
[selfpresentModalViewController:tweetSheet animated:YES];
}
else {
UIAlertView *alert = [[UIAlertViewalloc]initWithTitle:#"Sorry"message:#"You can't send a tweet right now, make sure your device has an internet connection and you have at least one Twitter account setup"delegate:selfcancelButtonTitle:#"Ok"otherButtonTitles:nil];
[alert show];
}
}

Related

Silent login using Username in Azure Active Directory in Xamarin

I am developing app using Xamarin Forms. I have created a directory on azure portal. As i see references over internet , active directory authentication uses Microsofts login page to log in.
I want to create native login form and pass user name to active directory and authenticate it.
Is it possible to pass user credentials programatically and authenticate user?
How can i pass user credentials?
I have tried following but i got "(411) Length required" exception
var request = WebRequest.Create(string.Format(#"https://login.microsoftonline.com/{0}/oauth2/token?client_id=5e811f4f-4fa4-451e-a439-ca05cabc02d7&grant_type=password&username=02atul.com#gmail.com&password=userpassword&scope=openid", tenant));
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
using (HttpWebResponse response = await request.GetResponseAsync() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
Debug.WriteLine("Error fetching data. Server returned status code: {0}", response.StatusCode);
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var content = reader.ReadToEnd();
if (string.IsNullOrWhiteSpace(content))
{
Debug.WriteLine("Response contained empty body...");
}
else {
Debug.WriteLine("Response Body: \r\n {0}", content);
}
}
}
My username is my email id. Is it correct user name? As i am getting bad request error now. What's missing?
Technically you could use username and password flow which is described in more detail here with ADAL.
However, you need to revisit your scenario and understand if it really accomplishes what the Azure Active Directory Platform is for.
Users use OAuth2 based authentication to get the security and safety of only having to share their passwords with trusted identity providers like MS, FB, Google, etc... In general, the safety conscious person will NOT want to type in a password into your random website, and trust that you do not abuse that information. If you want to use AAD, you should also use our login experiences, as this is really what the customer is paying for in our service in many regards.
EDIT: If ADAL no longer supports this flow, you can simply generate the http requests yourself:
POST: https://login.microsoftonline.com/xxxxx.onmicrosoft.com/oauth2/token
Content-Type: application/x-www-form-urlencoded
resource={resource}&client_id={clientId}&grant_type=password&username={userName}&password={password}&scope=openid&client_secret={clientSecret}

iOS GET Twitter & Parse.com - Authorisation Method

I am developing an app for iOS. The app is to store the tweetIDs of the tweets the user has made which include another twitter handle in.
I can successfully log a user into a twitter account on the device through the Social Framework and call the API to receive and page through past tweets. However this takes up a lot of bandwidth on the device & I would prefer for the server (Parse.com) to do this for me, as it is here where the IDs will be stored. Is the social framework enough for this or do I need to create a Oauth from scratch for Java SDK for coding the parse server?
Thanks
D
NSString * requestString = [NSString stringWithFormat:#"https://api.twitter.com/1.1/users/show.json?screen_name=%#", user.username];
NSURL *verify = [NSURL URLWithString:requestString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:verify];
[[PFTwitterUtils twitter] signRequest:request];
NSURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&error];
You pass in the username of the user you want to authenticate for. Then create an NSDictionary object and use the 'NSJSONSerialization JSONObjectWithData:options: method with the NSData data object that you get from the request to be able to use the results of the response. Happy coding.

"push notifications at least one user should be subscribed for APNS" Quickblox

Hi I have an issue here with regards to sending Push Notifications from my app. I can send them from the admin panel and they are received by the device but not from device to device. I have re-uploaded both development and production certificates on a couple of occasions now. Also push notifications can only be sent from the admin panel in the sandbox environment (no errors) and not the production environment (No recipients. At least one user should be subscribed for APNS (Apple Push) (through SDK or REST API). Can someone help please?
//
NSString *message = #"Testing APNS!";
NSMutableDictionary *payload = [NSMutableDictionary dictionary];
NSMutableDictionary *aps = [NSMutableDictionary dictionary];
[aps setObject:#"default" forKey:QBMPushMessageSoundKey];
[aps setObject:message forKey:QBMPushMessageAlertKey];
[payload setObject:aps forKey:QBMPushMessageApsKey];
QBMPushMessage *pushMessage = [[QBMPushMessage alloc] initWithPayload:payload];
// Send push to user
[QBMessages TSendPush:pushMessage toUsers:self.opponent.login delegate:self];
//
[QBMessages TSendPush:pushMessage toUsers:self.opponent.login delegate:self];
You can's send push notification to user's login, you have to use user's ID
For example:
[QBMessages TSendPush:pushMessage toUsers:#"22,33,77" delegate:self];

FB iOS SDK Custom Token Caching issue

I am trying to build an iOS application with a custom token caching mechanism. I authenticate to FB on the device and I store the FB access token on my server against a session token on my server and then make FB API requests from the server.
The FB Login works fine. I am able to cache the token onto my server. But the real problem happens when I run the app the next time after I logged into FB.
This is the flow I follow to check if my app is logged into FB.
1) Hit a url on my server to get the FBAccessToken for a given session token for my application. This is an asynchronous request.
2) The asynchronous request callback is fired. If a token is present, cache it in my custom FBSessionTokenCachingStrategy class.
3) In the callback I initialize a FBSession object using:
FBSession *session = [[FBSession alloc] initWithAppID:nil permissions:#[#"basic_info"] urlSchemeSuffix:nil tokenCacheStrategy:self.tokenCache];
Then, I check the session.state. If I get a FBSessionCreatedTokenLoaded, then I decide to proceed with the openBehaviour method. However, I get a FBSessionStateCreated instead of FBSessionStateCreatedTokenLoaded even when a token has been cached on the server and the fetchFBAccessTokenData returns a FBAccessTokenData object.
Wonder why this happens?
Here is my implementation of the fetchFBAccessTokenData method of my custom FBSessionTokenCachingStrategy class:
-(FBAccessTokenData*) fetchFBAccessTokenData {
NSLog(#"Fetching FB Access token");
if (self.fbTokenData != nil) {
NSLog(#"Found FB Token");
FBAccessTokenData *fbTokenData = [FBAccessTokenData createTokenFromString: [self.fbTokenData objectForKey:#"fb_token"] permissions:nil expirationDate:nil loginType:1 refreshDate:nil];
NSLog(#"%#",fbTokenData.accessToken);
return fbTokenData;
}
return nil;
}
It returns an FBAccessTokenData object but I still get an incorrect session state.
Does this happen because I am not returning the cached token correctly? I am implementing my code based on the standard example given for custom caching in the FB IOS SDK documentation.
It looks like your strategy is returning an FBAccessTokenData that has no permissions (which is not entirely unreasonable for your purposes unless you were to store permissions as well). When you init the session, however, specifying "basic_info" (while generally a good best practice, and required when asking for login that would prompt UI) will cause it to check that "basic_info" is included in the cached token. Since it is not, it will not load the cached token. For your purposes, you ought to be able to init the session with a nil permission array.

Looking for OAuth version of Twitter code for iOS client

Am learning about iOS programming from book Head First iPhone Programming. In one exercise, they have sample code for Twitter which uses basic authorization. Now that Twitter uses OAuth, how can I get OAuth code so that I can test my client? Do I need to register my app with Twitter? How do I do that, since it's only a test app?
Here is the basic authorization version of the code; I'm looking for the OAuth version:
//TWITTER BLACK MAGIC
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://YOUR_TWITTER_USERNAME:YOUR_TWITTER_PASSWORD#twitter.com/statuses/update.xml"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[theRequest setHTTPMethod:#"POST"];
[theRequest setHTTPBody:[[NSString stringWithFormat:#"status=%#", themessage] dataUsingEncoding:NSASCIIStringEncoding]];
NSURLResponse* response;
NSError* error;
NSData* result = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSLog(#"%#", [[[NSString alloc] initWithData:result encoding:NSASCIIStringEncoding] autorelease]);
//END TWITTER BLACK MAGIC
To get Twitter oAuth access you will need to create app on http://dev.twitter.com and retrieve Consumer Key and Consumer Auth.
Perhaps this tutorial will help you:
http://mobile.tutsplus.com/tutorials/iphone/twitter-api-iphone/

Resources