Login with Twitter using Swift and OAuth in ios [closed] - ios

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I am very new to Swift and IOS. I want to implement the login with twitter account using OAuth in my swift iOS application.
I implemented it but I got
[{“message”:”Could not authenticate you”,”code”:32}]}
error

Yes it is quite heavy to implement OAuth of the twitter to the iOS. In my applications I am using ACAccountStore for authentication with the twitter. For you I can recommend to use this library.

Too Easy
I used framework STTwitter which is very nice. also watch this video Twitter app only Authentication and check STTwitterDemoiOS demo to more clear.
Step 1: Create Twitter app and get Consumer key and Consumer secrete.
Step 2: Download STTwitter Framework and Drag and drop file into your Xcode project.
Step 3: UIWebView/Safari Login
- (IBAction)signInWithTwitterClicked:(id)sender {
//login by website
self.twitter = [STTwitterAPI twitterAPIWithOAuthConsumerKey:CONSUMER_KEY
consumerSecret:CONSUMER_SECRETE];
[_twitter postTokenRequest:^(NSURL *url, NSString *oauthToken) {
NSLog(#"URL: %#", url);
NSLog(#"OauthToken: %#", oauthToken);
// if(1) {
// [[UIApplication sharedApplication] openURL:url];
//} else {
//WebViewVc taken from STTwitterDemoiOS demo.
WebViewVC *webViewVC = [self.storyboard instantiateViewControllerWithIdentifier:#"WebViewVC"];
[self presentViewController:webViewVC animated:YES completion:^{
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webViewVC.webView loadRequest:request];
}];
// }
} authenticateInsteadOfAuthorize:NO
forceLogin:#(YES)
screenName:nil
oauthCallback:#"myapp://twitter_access_tokens/"
errorBlock:^(NSError *error) {
NSLog(#"-- error: %#", error);
// _loginStatusLabel.text = [error localizedDescription];
}];
}
//Step 4 and Step 5 imp to callback to our application
Step 4: Configured info.plist as shown in image.
Step 5: Handle application Delegate method
- (NSDictionary *)parametersDictionaryFromQueryString:(NSString *)queryString {
NSMutableDictionary *md = [NSMutableDictionary dictionary];
NSArray *queryComponents = [queryString componentsSeparatedByString:#"&"];
for(NSString *s in queryComponents) {
NSArray *pair = [s componentsSeparatedByString:#"="];
if([pair count] != 2) continue;
NSString *key = pair[0];
NSString *value = pair[1];
md[key] = value;
}
return md;
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
//Twitter integration
// if ([[url scheme] isEqualToString:#"myapp"] == NO) return NO;
NSDictionary *d = [self parametersDictionaryFromQueryString:[url query]];
NSString *token = d[#"oauth_token"];
NSString *verifier = d[#"oauth_verifier"];
// NSLog(#"Twitter Token=> %#\n Twitter Verifier=>%#",token,verifier);
ViewController *vc = (ViewController *)[[self window] rootViewController];
StartupViewController *startVc=(StartupViewController *)[[vc childViewControllers] objectAtIndex:0];
[startVc setOAuthToken:token oauthVerifier:verifier];
//startVc is my controller where my "Login with twitter" button is there.
//if no Facebook integration then return YES instead if return //[FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
//Facebook Integration
return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
}
Step 6: Get User credentials.
-(void)setOAuthToken:(NSString *)token oauthVerifier:(NSString *)verifier {
// in case the user has just authenticated through WebViewVC
[self dismissViewControllerAnimated:YES completion:^{
//Dismiss presented controller.
}];
[_twitter postAccessTokenRequestWithPIN:verifier successBlock:^(NSString *oauthToken, NSString *oauthTokenSecret, NSString *userID, NSString *screenName) {
//Here is your Ans.
NSLog(#"SUCCESS screenName: %# ,userID=%#", screenName,userID);
} errorBlock:^(NSError *error) {
NSLog(#"-- %#", [error localizedDescription]);
}];
}
hope this help some one.

Related

LinkedIn Authorization Screen Not Appearing

I have integrated official LinkedIn iOS SDK(https://developer.linkedin.com/downloads#iossdk). While clicking on "Share via LinkedIn" in my iOS app, it opens LinkedIn official iOS app on my iOS device & ask for login, but after logging user stays on LinkedIn App only not coming back to my iOS App & no authorization screen displayed. (I am using iPad with iOS 8 & 9) Is there any suggestion?
My Plist Settings to configure Linkedin:
Sample Code:
-(void)postOnLinkedIn:(NSMutableDictionary *)dictData {
NSMutableDictionary *dictCode = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"anyone",#"code", nil];
[dictData setObject:#"Check out developer.linkedin.com! http://linkd.in/1FC2PyG" forKey:#"comment"];
[dictData setObject:dictCode forKey:#"visibility"];
NSString *url = #"https://api.linkedin.com/v1/people/~/shares";
NSString *payload = [NSString stringWithFormat:#"%#",dictData];
NSLog(#"%#",payload);
// NSString *payload = [NSString initWithString:#"{
// \"comment\":\"Check out developer.linkedin.com! http://linkd.in/1FC2PyG\",
// \"visibility\":{ \"code\":\"anyone\" }
// }"];
if ([LISDKSessionManager hasValidSession]) {
[[LISDKAPIHelper sharedInstance] postRequest:url stringBody:payload
success:^(LISDKAPIResponse *response) {
// do something with response
}
error:^(LISDKAPIError *apiError) {
// do something with error
}];
}
else {
[self connectToLinkedIn];
}
}
-(void)connectToLinkedIn {
[LISDKSessionManager createSessionWithAuth:[NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION,LISDK_EMAILADDRESS_PERMISSION,LISDK_W_SHARE_PERMISSION, nil]
state:#"state"
showGoToAppStoreDialog:YES
successBlock:^(NSString *returnState) {
NSLog(#"%s","success called!");
LISDKSession *session = [[LISDKSessionManager sharedInstance] session];
NSLog(#"value=%# isvalid=%#",[session value],[session isValid] ? #"YES" : #"NO");
}
errorBlock:^(NSError *error) {
//[self clearSession:<#(id)#>]
NSLog(#"%s %#","error called! ", [error description]);
//self.lastError = error;
// _responseLabel.text = [error description];
//[self updateControlsWithResponseLabel:YES];
}
];
}

share image on twitter and get favourites list from iOS native app

I found many tutorials online how to share image on twitter from an iOS app. But i want to know 2 things about social sharing with twitter-
If i post an image on twitter via my app, Can i get image id from twitter in callback method/block? If yes then how?
If i fetch favourites of a user, is the response include text posted with that image? I checked for the same on twitter Rest API doc that there is a text property returned in the response.
Now my question is that if i post some text with image via my iOS app and later make this post favourite in twitter app and now i get my favourites list through twitter rest API in my app, does the text property in the response is same that i posted with my post?
Edit about #1 above:- from SLComposeViewControllerResult docs i found that completion handler return one of
typedef NS_ENUM (NSInteger,
SLComposeViewControllerResult ) {
SLComposeViewControllerResultCancelled,
SLComposeViewControllerResultDone
};
constant so there is no info about image just posted. Am i right? If not please give me some reference about how to get image id please.
Here I have customize alertView,NSLog,etc. You ignore that.
Here is the code to share to twitter by using STTwitter library
- (void)shareToTwitter
{
APP_DELEGATE.navController = self.navigationController;
NSString *strTwitterToken = [[NSUserDefaults standardUserDefaults] objectForKey:#"TwitterToken"];
NSString *strTwitterTokenSecret = [[NSUserDefaults standardUserDefaults] objectForKey:#"TwitterTokenSecret"];
if (strTwitterToken && strTwitterTokenSecret)
{
self.twitter = [STTwitterAPI twitterAPIWithOAuthConsumerKey:TwitterConsumerKey consumerSecret:TwitterSecretKey oauthToken:strTwitterToken oauthTokenSecret:strTwitterTokenSecret];
[self.twitter verifyCredentialsWithSuccessBlock:^(NSString *username) {
DLogs(#"Twitter User Name");
[self twitterMediaUpload];
} errorBlock:^(NSError *error) {
DLogs(#"-- error: %#", error);
[AppConstant showAutoDismissAlertWithMessage:[error localizedDescription] onView:self.view];
[self safariLoginTwitter];
}];
}
else
{
[self safariLoginTwitter];
}
}
-(void)safariLoginTwitter
{
// [APP_CONSTANT getNativeTwitterAccountAccessToken:^(id result) {
//
// }];
self.twitter = [STTwitterAPI twitterAPIWithOAuthConsumerKey:TwitterConsumerKey
consumerSecret:TwitterSecretKey];
[self.twitter postTokenRequest:^(NSURL *url, NSString *oauthToken) {
DLogs(#"-- url: %#", url);
DLogs(#"-- oauthToken: %#", oauthToken);
[[UIApplication sharedApplication] openURL:url];
} authenticateInsteadOfAuthorize:NO
forceLogin:#(YES)
screenName:nil
oauthCallback:#"myapp://twitter_access_tokens/"
errorBlock:^(NSError *error) {
DLogs(#"-- error: %#", error);
[AppConstant showAutoDismissAlertWithMessage:[error localizedDescription] onView:self.view];
}];
}
- (void)setOAuthToken:(NSString *)token oauthVerifier:(NSString *)verifier {
[self.twitter postAccessTokenRequestWithPIN:verifier successBlock:^(NSString *oauthToken, NSString *oauthTokenSecret, NSString *userID, NSString *screenName) {
DLogs(#"-- screenName: %#", screenName);
/*
At this point, the user can use the API and you can read his access tokens with:
_twitter.oauthAccessToken;
_twitter.oauthAccessTokenSecret;
You can store these tokens (in user default, or in keychain) so that the user doesn't need to authenticate again on next launches.
Next time, just instanciate STTwitter with the class method:
+[STTwitterAPI twitterAPIWithOAuthConsumerKey:consumerSecret:oauthToken:oauthTokenSecret:]
Don't forget to call the -[STTwitter verifyCredentialsWithSuccessBlock:errorBlock:] after that.
*/
[[NSUserDefaults standardUserDefaults] setObject:self.twitter.oauthAccessToken forKey:#"TwitterToken"];
[[NSUserDefaults standardUserDefaults] setObject:self.twitter.oauthAccessToken forKey:#"TwitterTokenSecret"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self twitterMediaUpload];
} errorBlock:^(NSError *error) {
[AppConstant showAutoDismissAlertWithMessage:[error localizedDescription] onView:self.view];
DLogs(#"-- %#", [error localizedDescription]);
}];
}
-(void)twitterMediaUpload
{
// ProfileImageBO *objProfImg = nil;
//
// if ([self.objProfile.arrUserImages count]) {
// objProfImg = [self.objProfile.arrUserImages objectAtIndex:0];
// }
[APP_CONSTANT showLoaderWithTitle:#"posting" onView:self.view];
// NSURL *urlProfImg = [NSURL URLWithString:[objProfImg.imageUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *screenshotUrl = [self getScreenshotUrl];
[self.twitter postMediaUpload:screenshotUrl uploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
DLogs(#"uploading");
} successBlock:^(NSDictionary *imageDictionary, NSString *mediaID, NSString *size) {
DLogs(#"imageDictionary = %#, mediaID = %#, size %#",imageDictionary.description,mediaID,size);
[self postToTheTwitterWithMediaId:mediaID];
} errorBlock:^(NSError *error) {
DLogs(#"Error in uploading media, try again ...");
[APP_CONSTANT hideLoader];
[AppConstant showAutoDismissAlertWithMessage:error.localizedDescription onView:self.view];
}];
}
-(void)postToTheTwitterWithMediaId:(NSString *)mediaID
{
NSString *msg = [NSString stringWithFormat:#"Check out My Profile"];
[self.twitter postStatusUpdate:msg inReplyToStatusID:nil mediaIDs:[NSArray arrayWithObject:mediaID] latitude:nil longitude:nil placeID:nil displayCoordinates:nil trimUser:nil successBlock:^(NSDictionary *status) {
DLogs(#"Description %#",status.description);
[self showNotificationToastWithMessage:TwitterPostSuccess];
[APP_CONSTANT hideLoader];
} errorBlock:^(NSError *error) {
DLogs(#"Twitter posting error %#",error.description);
[APP_CONSTANT hideLoader];
[AppConstant showAutoDismissAlertWithMessage:error.localizedDescription onView:self.view];
}];
}
For your second question: Yes, you will get the same text in the response
And This is the code to get favorite list
-(void)getFavListTwitter
{
[self.twitter getFavoritesListWithSuccessBlock:^(NSArray *statuses) {
DLogs(#"%#",statuses.description);
} errorBlock:^(NSError *error) {
DLogs(#"%#",error.description);
}];
}

Upload Facebook Photo And Auto Log User Out (Kiosk App)

I have an iPad app designed for use in a kiosk environment.
The user flow should be
Take Photo
Choose photo from iPad Album view
Share to Facebook and / or Twitter
Automatically log user out after image has been posted
I have the auto-logout of Twitter working properly, my issue is with the Facebook portion.
I have implemented the Graph API for internal testing, and would love to be able to post a complete story this way, but I don't think there is a way to log out from the Facebook app once the authorization and post is complete.
For a fallback, I can use the Feed Dialog and auto-logout from there, but as far as I can tell, there is no way to upload a local image for sharing to Facebook from there.
My Facebook Sharing code is as follows:
- (IBAction)facebookShare:(id)sender {
/// Package the image inside a dictionary
NSArray* image = #[#{#"url": self.mergeImages, #"user_generated": #"true"}];
// Create an object
id<FBGraphObject> object =
[FBGraphObject openGraphObjectForPostWithType:#"me/feed:photo"
title:#"a photo"
image:self.mergeImages
url:nil
description:nil];
// Create an action
id<FBOpenGraphAction> action = (id<FBOpenGraphAction>)[FBGraphObject graphObject];
// Set image on the action
[action setObject:image forKey:#"image"];
// Link the object to the action
[action setObject:object forKey:#"photo"];
// Hardcode the location based on Facebook Place ID
id<FBGraphPlace> place = (id<FBGraphPlace>)[FBGraphObject graphObject];
[place setId:#"279163865580772"]; // Singley + Mackie
[action setPlace:place];
// Check if the Facebook app is installed and we can present the share dialog
FBOpenGraphActionShareDialogParams *params = [[FBOpenGraphActionShareDialogParams alloc] init];
params.action = action;
params.actionType = #"me/feed:share";
// If the Facebook app is installed and we can present the share dialog
if([FBDialogs canPresentShareDialogWithOpenGraphActionParams:params]) {
// Show the share dialog
[FBDialogs presentShareDialogWithOpenGraphAction:action
actionType:#"photo_overlay:share"
previewPropertyName:#"photo"
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if(error) {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
// NSLog([NSString stringWithFormat:#"Error publishing story: %#", error.description]);
} else {
// Success
NSLog(#"result %#", results);
}
}];
// If the Facebook app is NOT installed and we can't present the share dialog
} else {
// Put together the Feed dialog parameters
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"name",
#"caption",
#"description",
#"link",
#"picture",
nil];
// Show the feed dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
// NSLog([NSString stringWithFormat:#"Error publishing story: %#", error.description]);
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User cancelled.
NSLog(#"User cancelled.");
} else {
// Handle the publish feed callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"post_id"]) {
// User cancelled.
NSLog(#"User cancelled.");
} else {
// User clicked the Share button
NSString *result = [NSString stringWithFormat: #"Posted story, id: %#", [urlParams valueForKey:#"post_id"]];
NSLog(#"result %#", result);
}
}
}
// Auto log the user out
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSLog(#"defaults fbDidLogout ........%#",defaults);
if ([defaults objectForKey:#"FBAccessTokenKey"])
{
[defaults removeObjectForKey:#"FBAccessTokenKey"];
[defaults removeObjectForKey:#"FBExpirationDateKey"];
[defaults synchronize];
}
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
NSString* domainName = [cookie domain];
NSRange domainRange = [domainName rangeOfString:#"facebook"];
if(domainRange.length > 0)
{
[storage deleteCookie:cookie];
}
}
[FBSession.activeSession closeAndClearTokenInformation];
}];
}
}
// A function for parsing URL parameters.
- (NSDictionary*)parseURLParams:(NSString *)query {
NSArray *pairs = [query componentsSeparatedByString:#"&"];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
for (NSString *pair in pairs) {
NSArray *kv = [pair componentsSeparatedByString:#"="];
NSString *val =
[kv[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
params[kv[0]] = val;
}
return params;
}
I have searched Stack Overflow far and wide for an answer to this, but have found no solutions.
I was finally able to figure this out! Posting the answer here to hopefully benefit others who are in the same situation.
First, add the following to your AppDelegate.m:
-(BOOL) application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication fallbackHandler:^(FBAppCall *call) {
// Facebook SDK * App Linking *
// For simplicity, this sample will ignore the link if the session is already
// open but a more advanced app could support features like user switching.
if (call.accessTokenData) {
if ([FBSession activeSession].isOpen) {
NSLog(#"INFO: Ignoring app link because current session is open.");
}
else {
[self handleAppLink:call.accessTokenData];
}
}
}];
}
// Helper method to wrap logic for handling app links.
- (void)handleAppLink:(FBAccessTokenData *)appLinkToken {
// Initialize a new blank session instance...
FBSession *appLinkSession = [[FBSession alloc] initWithAppID:nil
permissions:nil
defaultAudience:FBSessionDefaultAudienceNone
urlSchemeSuffix:nil
tokenCacheStrategy:[FBSessionTokenCachingStrategy nullCacheInstance] ];
[FBSession setActiveSession:appLinkSession];
// ... and open it from the App Link's Token.
[appLinkSession openFromAccessTokenData:appLinkToken
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
// Forward any errors to the FBLoginView delegate.
if (error) {
//[self.loginViewController loginView:nil handleError:error];
}
}];
}
Wherever you are calling the posting action in your app, add this line to your header file:
#property (strong, nonatomic) FBRequestConnection *requestConnection;
And the following to your implementation file:
#synthesize requestConnection;
- (IBAction)facebookShare:(id)sender {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_actions", #"publish_checkins", nil];
UIImage *img = self.facebookImage;
[FBSession openActiveSessionWithPublishPermissions:permissions
defaultAudience:FBSessionDefaultAudienceEveryone allowLoginUI:YES
completionHandler:^(FBSession *session,FBSessionState s, NSError *error) {
[FBSession setActiveSession:session];
if (!error) {
// Now have the permission
[self processPostingImage:img WithMessage:#"Enter_your_message_here"];
} else {
// Facebook SDK * error handling *
// if the operation is not user cancelled
if (error.fberrorCategory != FBErrorCategoryUserCancelled) {
[self presentAlertForError:error];
}
}
}];
}
-(void)logout {
[FBSession.activeSession closeAndClearTokenInformation];
[FBSession.activeSession close];
[FBSession setActiveSession:nil];
}
- (void)processPostingImage:(UIImage *) img WithMessage:(NSString *)message {
FBRequestConnection *newConnection = [[FBRequestConnection alloc] init];
FBRequestHandler handler =
^(FBRequestConnection *connection, id result, NSError *error) {
// output the results of the request
[self requestCompleted:connection forFbID:#"me" result:result error:error];
};
FBRequest *request=[[FBRequest alloc] initWithSession:FBSession.activeSession graphPath:#"me/photos" parameters:[NSDictionary dictionaryWithObjectsAndKeys:UIImageJPEGRepresentation(img, 0.7),#"source",message,#"message",#"{'value':'EVERYONE'}",#"privacy", nil] HTTPMethod:#"POST"];
[newConnection addRequest:request completionHandler:handler];
[self.requestConnection cancel];
self.requestConnection = newConnection;
[newConnection start];
}
// FBSample logic
// Report any results. Invoked once for each request we make.
- (void)requestCompleted:(FBRequestConnection *)connection
forFbID:fbID
result:(id)result
error:(NSError *)error
{
// not the completion we were looking for...
if (self.requestConnection &&
connection != self.requestConnection)
{
return;
}
// clean this up, for posterity
self.requestConnection = nil;
if (error)
{
}
else
{
[self logout];
};
}
- (void) presentAlertForError:(NSError *)error {
// Facebook SDK * error handling *
// Error handling is an important part of providing a good user experience.
// When fberrorShouldNotifyUser is YES, a fberrorUserMessage can be
// presented as a user-ready message
if (error.fberrorShouldNotifyUser) {
// The SDK has a message for the user, surface it.
[[[UIAlertView alloc] initWithTitle:#"Something Went Wrong"
message:error.fberrorUserMessage
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
} else {
}
}
Note:
To make this work with auto-logout, you also have to disable Safari on the device. This can be done by going to Settings > General > Restrictions > Allow Safari > Off. Once that is turned off, the Facebook IBAction will popup a UIWebView inside the app itself. When tapped, the current user can enter their Facebook credentials, then the app will post the image, and log the user out so the next user can use the app without having access to the previous user's Facebook details.

iOS custom url scheme

I'm creating an app that uses a custom url scheme, I have it all set up and it works when opening the app up, however, I now want to be able to add a single string to the url so that the person that opens the app can see that string. I'm really struggling with this, can someone help me please?
Here is my code
- (NSDictionary*)parseURLParams:(NSString *)query
{
NSArray *pairs = [query componentsSeparatedByString:#"&"];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
for (NSString *pair in pairs)
{
NSArray *kv = [pair componentsSeparatedByString:#"="];
NSString *val = [[kv objectAtIndex:1]
stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[params setObject:val forKey:[kv objectAtIndex:0]];
}
return params;
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
NSString *title = [alertView buttonTitleAtIndex:buttonIndex];
if([title isEqualToString:#"Send Challenge"])
{
[FBWebDialogs presentRequestsDialogModallyWithSession:nil
message:[NSString stringWithFormat:#"I just scored %i points on this great game, called SumsUp. can you beat it?!", gameScore]
title:nil
parameters:nil
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error)
{
// Error launching the dialog or sending the request.
NSLog(#"Error sending request.");
}
else
{
if (result == FBWebDialogResultDialogNotCompleted)
{
// User clicked the "x" icon
NSLog(#"User canceled request.");
}
else
{
// Handle the send request callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"request"])
{
// User clicked the Cancel button
NSLog(#"User canceled request.");
}
else
{
// User clicked the Send button
NSString *requestID = [urlParams valueForKey:#"request"];
NSLog(#"Request ID: %#", requestID);
}
}
}
}];
}
I have got the custom url setup in the P-List.
in my app delegate I have:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
UIAlertView *alertView;
NSString *text = [NSString stringWithFormat: #"url recieved: %#", url];
alertView = [[UIAlertView alloc] initWithTitle:#"" message:text delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication withSession:[PFFacebookUtils session]];
}
I hope this makes sense and somebody can help me. If any more information is required please let me know?
Thanks Graham
I had problem with custom URL Scheme on ios v. 9.x.x. when i tried open Youtube URL by App. I have found interesting fact when i have browsed through network.
iOS 9 requires your app to pre-register application schemes it intends to call.
Open your YourApp-Info.plist file and add the key, LSApplicationQueriesSchemes.
List item under LSApplicationQueriesSchemes, add a
new item with the value youtube (in my case).
<key>LSApplicationQueriesSchemes</key>
<array>
<string>youtube</string>
</array>
My solution is simpler. I hope you will find it useful.
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
// Example URL: myapp://myapp.com/showString/yourString
BOOL isMyAppURL = [[url scheme] isEqualToString:#"myapp"];
if (isMyAppURL)
{
NSArray* pathComponents = [url pathComponents];
NSString *command = pathComponents[0];
// Check for showString command.
if ([command isEqualToString:#"showString"])
{
NSString *stringToShow = [pathComponents[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"String to show: %#", stringToShow);
}
}
return isMyAppURL;
}
This should point you to the right direction.

Twitter Authorization Login

I'm using STTwitterto interface with Twitter in an iOS app I'm changing for someone. When I call the twitter authorization page for the first time with the following code:
- (void)newUser
{
[[NetworkManager sharedInstance] resetTwitterAPI];
[[[NetworkManager sharedInstance] twitterAPI] postTokenRequest:^(NSURL *url, NSString *oauthToken) {
[[UIApplication sharedApplication] openURL:url];
} oauthCallback:#"tweepr://twitter_access_token" errorBlock:^(NSError *error) {
NSLog(#"Error %s", __PRETTY_FUNCTION__);
}];
}
* Which, in turn, calls this:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
if (![[url scheme] isEqualToString:#"tweepr"]) {
return NO;
}
NSDictionary *d = [self parametersDictionaryFromQueryString:[url query]];
NSString *token = d[#"oauth_token"];
NSString *verifier = d[#"oauth_verifier"];
[[UserLoadingRoutine sharedRoutine] setOAuthToken:token verifier:verifier];
return YES;
}
* Which finally calls this:
- (void)setOAuthToken:(NSString *)token verifier:(NSString *)verifier
{
[[[NetworkManager sharedInstance] twitterAPI] postAccessTokenRequestWithPIN:verifier successBlock:^(NSString *oauthToken, NSString *oauthTokenSecret, NSString *userID, NSString *screenName) {
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict[#"nickname"] = screenName;
dict[#"token"] = oauthToken;
dict[#"secret"] = oauthTokenSecret;
dict[#"user_id"] = userID;
self.userDict = dict;
NSMutableArray *users = [self.availableUsers mutableCopy];
if (![users containsObject:dict]) {
[users addObject:dict];
}
self.availableUsers = [users copy];
[[NSUserDefaults standardUserDefaults] setObject:self.availableUsers forKey:#"availableUsers"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self selectUserWithIdentifier:dict[#"nickname"]];
} errorBlock:^(NSError *error) {
NSLog(#"Error");
}];
}
The twitter authorization page, the first time it comes up, has login and password fields to fill in as shown below at This Screenshot. If I bring the authorization page up again via the above code to authorize under a different user, This Screenshot appears and I need to sign out on the top. Is there a way to do this progmatically?
Append &force_login=1 to the URL string in -[STTwitterOAuth postTokenRequest:oauthCallback:errorBlock:].
Let me know if it works.

Resources