I am developing an app with Twitter login. When I am checking Fabric, it doesn't contain Twitter login as it's no longer available via Fabric, so I am trying to implement it using Twitter Kit (Twitter Kit Link).
I have installed Twitter Kit on my app, when I am trying to run the app it crashes on
Twitter.sharedInstance().startWithConsumerKey(<key>, consumerSecret: <secret>)
Error: terminating with uncaught exception of type NSException
Any solutions...
try this code
add this gradle line in you project
compile 'com.twitter.sdk.android:twitter:3.0.0'
Write in your Activity/Fragment
//Your Custom Button
private ivTwitter;
//Twitter Login Button
private TwitterLoginButton ivTwitterMain;
//init twitter
TwitterConfig config = new TwitterConfig.Builder(this)
.logger(new DefaultLogger(Log.DEBUG))
.twitterAuthConfig(new TwitterAuthConfig(Const.CONSUMER_KEY, Const.CONSUMER_SECRET))
.debug(false)
.build();
Twitter.initialize(config);
//find your button
ivTwitter = (ImageView) findViewById(R.id.ivTwitter);
ivTwitterMain = (TwitterLoginButton)findViewById(R.id.ivTwitterMain);
//twitter login callback
ivTwitterMain.setCallback(new Callback<TwitterSession>() {
#Override
public void success(Result<TwitterSession> result) {
// Do something with result, which provides a TwitterSession for making API calls
TwitterSession session = TwitterCore.getInstance().getSessionManager().getActiveSession();
TwitterAuthToken authToken = session.getAuthToken();
String token = authToken.token;
String secret = authToken.secret;
getTwitterUserProfile(session);
}
#Override
public void failure(TwitterException exception) {
// Do something on failure
Log.d(Const.FRAGMENT_REGISTER, exception.getMessage());
}
});
getTwitterUserProfile code
private void getTwitterUserProfile(TwitterSession session) {
AccountService accountService = new TwitterApiClient(session).getAccountService();
Call<User> callback = accountService.verifyCredentials(true, true, true);
callback.clone().enqueue(new Callback<User>() {
#Override
public void success(Result<User> result) {
Log.d("NAME ", result.data.name);
Log.d("EMAIL", result.data.email);
Log.d("PICTURE ", result.data.profileImageUrl);
}
#Override
public void failure(TwitterException exception) {
}
});
}
at last generate Click event of custom button
ivTwitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//twitter login button
ivTwitterMain.performClick();
}
});
I'm assuming that you have already read the twitter official documentation about "Installation" of the TwitterKit in iOS app. I had such experience and the only thing that worked and wasn't in the documentation was this:
In your Info.plist file make sure that "twitterkit-yourAppKey" in
your CFBundleURLSchemes is Item 0.
I've answered this here. Hope it helps you :)
Related
I am trying to add Google Play Services to my Xamarin Android app.
I am using Play Games Services v2 SDK and trying to follow this tutorial from the Official documentation.
The Java code for signing in would be that:
GamesSignInClient gamesSignInClient = PlayGames.getGamesSignInClient(getActivity());
gamesSignInClient.isAuthenticated().addOnCompleteListener(isAuthenticatedTask -> {
boolean isAuthenticated =
(isAuthenticatedTask.isSuccessful() &&
isAuthenticatedTask.getResult().isAuthenticated());
if (isAuthenticated) {
// Continue with Play Games Services
} else {
// Disable your integration with Play Games Services or show a
// login button to ask players to sign-in. Clicking it should
// call GamesSignInClient.signIn().
}
});
How can I translate it to C#?
Anyone can help me please?
This is my best attempt, but I am getting an exception on SetJniIdentityHashCode method not implemented.
using Android.Gms.Games;
using Android.Gms.Tasks;
// ...
PlayGamesSdk.Initialize(this);
IGamesSignInClient gamesSignInClient = PlayGames.GetGamesSignInClient(this);
gamesSignInClient.IsAuthenticated().AddOnCompleteListener(
new OnCompleteListener()
);
// ...
public class OnCompleteListener : Java.Lang.Object, IOnCompleteListener
{
public void Disposed()
{
throw new NotImplementedException();
}
public void DisposeUnlessReferenced()
{
throw new NotImplementedException();
}
public void Finalized()
{
throw new NotImplementedException();
}
public void OnComplete(Task task)
{
//var isAuthenticated =
// (task.IsSuccessful &&
// ((????)task.Result).isAuthenticated())
//if (isAuthenticated)
//{
// // Continue with Play Games Services
//}
//else
//{
// // Disable your integration with Play Games Services or show a
// // login button to ask players to sign-in. Clicking it should
// // call GamesSignInClient.signIn().
//}
}
public void SetJniIdentityHashCode(int value)
{
throw new NotImplementedException();
}
public void SetJniManagedPeerState(JniManagedPeerStates value)
{
throw new NotImplementedException();
}
public void SetPeerReference(JniObjectReference reference)
{
throw new NotImplementedException();
}
}
I managed to get the authentication result in the following way, probably was just using the wrong references.
public class TaskCompleteListener : Java.Lang.Object, IOnCompleteListener
{
public void OnComplete(Android.Gms.Tasks.Task task)
{
var isAuthenticated = task.IsSuccessful &&
((AuthenticationResult)task.Result).IsAuthenticated;
if (isAuthenticated)
{
// Continue with Play Games Services
}
else
{
// Disable your integration with Play Games Services or show a
// login button to ask players to sign-in. Clicking it should
// call GamesSignInClient.signIn().
}
}
}
In Android Studios BiometricPrompt API contains a callback named onAuthenticationError which gets triggered when the user touch outside the BiometricPrompt dialog and once a user tries to input an invalid Biometric to the device. But the BiometricPrompt API available in Xamarin.Android platform doesn't provide onAuthenticationError callback.
I created an android application using Android Studios to check BiometricPrompt API there I could access the callback named onAuthenticationError. Then I deployed the application to a device and debugged the application. The above mentioned callback got triggered when I touched any area outside the BiometricPrompt dialog and it also got triggered every time I provided BiometricPrompt with a invalid input more than 5 times.
Then I tried developing the same application in Xamain.Android and there I was unable to find any callback named onAuthenticationError. When I deployed and tested the application in a device as the above-mentioned callback was not available I couldn't handle the 2 scenarios
where when the user touches any area outside the BiometricPrompt dialog and when user provides the BiometricPrompt with an invalid input more than 5 times.
My Native android code snippet.
#RequiresApi(api = Build.VERSION_CODES.P)
private BiometricPrompt.AuthenticationCallback getAuthenticationCallback() {
return new BiometricPrompt.AuthenticationCallback() {
#Override
** public void onAuthenticationError(int errorCode,
CharSequence errString) {
notifyUser("Authentication error: " + errString);
super.onAuthenticationError(errorCode, errString);
}**
#Override
public void onAuthenticationHelp(int helpCode,
CharSequence helpString) {
super.onAuthenticationHelp(helpCode, helpString);
}
#Override
public void onAuthenticationFailed() {
super.onAuthenticationFailed();
}
#Override
public void onAuthenticationSucceeded(
BiometricPrompt.AuthenticationResult result) {
notifyUser("Authentication Succeeded");
super.onAuthenticationSucceeded(result);
}
};
}
My Xamarin.Android code snippet
public class BiometricAuthCallBacks : BiometricPrompt.AuthenticationCallback
{
public TaskCompletionSource<LocalAuthStatus> promise = new TaskCompletionSource<LocalAuthStatus>();
private int failCount;
public override void OnAuthenticationSucceeded(BiometricPrompt.AuthenticationResult result)
{
base.OnAuthenticationSucceeded(result);
promise.TrySetResult(LocalAuthStatus.Success);
//Success(result);
}
public override void OnAuthenticationFailed()
{
base.OnAuthenticationFailed();
failCount++;
if (failCount>=5)
{
promise.TrySetResult(LocalAuthStatus.Fail);
}
//Failed();
}
public override void OnAuthenticationHelp([GeneratedEnum] BiometricAcquiredStatus helpCode, ICharSequence helpString)
{
base.OnAuthenticationHelp(helpCode, helpString);
promise.TrySetResult(LocalAuthStatus.Error);
//Help(helpCode, helpString);
}
}
My Question is why can't I access onAuthenticationError callback from Xamarin.Android platform and how can I resolve this?
I want to login into Facebook and share some info. Here is code
using UnityEngine;
using System.Collections.Generic;
using Facebook.Unity;
using System;
public class FBManager : MonoBehaviour {
void Awake()
{
FB.Init(Init);
}
void Init()
{
Debug.Log("initialized");
}
public void Share()
{
if (FB.IsLoggedIn)
{
Debug.Log("going to call FB.ShareLink()");
FB.ShareLink(new Uri("http://www.google.com/"), "google", "google super search engine", null,ShareCallback);
}
else
{
Debug.Log("going to call Login()");
Login();
}
}
private void Login()
{
FB.LogInWithPublishPermissions(new List<string>() { "publish_actions" }, LoginCallback);
}
void LoginCallback(ILoginResult result)
{
Debug.Log("error: " + result.Error);
if (result.Error != null)
Debug.LogError(result.Error);
else
{
Debug.Log("logged? " + FB.IsLoggedIn);
Share();
}
}
void ShareCallback(IShareResult result)
{
if (result.Error != null)
Debug.LogError(result.Error);
else
Debug.Log("sharing done");
}
}
And when it calls Login() method it gives an error
2015-12-14 17:36:25.910 TheMyAppName[741:307812] *** Terminating app
due to uncaught exception 'InvalidOperationException', reason: 'fb0 is
not registered as a URL scheme. Please add it in your Info.plist'
How do I fix it? It happens only when I'm making XCODE project with Unity 5.3, in Unity 5.2 all is right.
probably something's wrong with fb Unity sdk. This is how you integrate FB SDK in iOS. So probably you should manually implement the step 3 in xCode. If it throws another similar error just copy the scheme from the error log and again add it to plist.
My lwuit application is working fine on Blackberry Simulator while on device the application installs successfully, starts normally, but where am having issues is on network connection. Trying to access network I get 400 Bad Request message. I don't no what am doing wrong, my network connection code is as below:
public ConnectionRequest prepareConnection(String page, String progressMsg, final int request)
{
final ConnectionRequest conR = new ConnectionRequest()
{
public void readResponse(InputStream input) throws IOException {
StringBuffer sb = new StringBuffer();
int ch;
while((ch=input.read()) != -1)
sb.append((char)ch);
httpResponse(sb.toString().trim(), request);
}
};
conR.setUrl(NetworkHandler.getURL()+page);
conR.setDuplicateSupported(true);
Progress progress = new Progress(progressMsg, conR)
{
public void actionCommand(Command command)
{
if(command.getCommandName().equals("Cancel"))
conR.kill();
}
};
conR.setDisposeOnCompletion(progress);
return conR;
}
private void login(String code)
{
Container container = Display.getInstance().getCurrent();
if(!validateLogin(container))
{
showDialogMessage("Alert", "Please enter your user name and password!");
return;
}
NetworkManager.getInstance().start();
ConnectionRequest conR = prepareConnection(NetworkHandler.LOGIN_PAGE, "Authenticating...", RequestType.LOGIN);
Dialog dialog = conR.getDisposeOnCompletion();
conR.setPost(true);
conR.addArgument("u", getFieldValue(findTxtUserName(container)));
conR.addArgument("p", getFieldValue(findTxtPassword(container)));
conR.addArgument("c", code);
NetworkManager.getInstance().addToQueue(conR);
dialog.show();
}
public void onLoginForm_BtnLoginAction(Component c, ActionEvent event) {
login("");
}
Please I want you guys to help me out.
Thanks in Advance.
The login me
This usually indicates a problem in APN configuration on the device. Normally Blackberry app's workaround incorrect APN configurations automatically which is a pretty difficult thing to do. CodenameOne does that seamlessly but LWUIT does not.
How do I create a link that will automatically make a user follow a certain Twitter user if they're logged in or send them to Twitter to login first if they're not? I had found how to do this about month or 2 ago but can't find it again. I think it was something basic like a link or a form post to something like twitter.com/[user]/follow.
I've looked at the API, but I'd need the user to authenticate themselves on my site, and I don't want to deal with that. I just want them to authenticate directly on Twitter and not worry about it. The way I had found was nice and simple and I just want to find that again.
Use Twitter's web intents.
While you can use the follow button, you can also send users directly to the Intent URL, like so:
https://twitter.com/intent/user?screen_name=NASA
how to use twitter api in my android application to implement follow button only
Android
http://code.google.com/p/android-hackathon-in-fukuoka/source/browse/trunk/sodefuri/src/jp/jagfukuoka/sodefuri/TimeLineActivity.java?spec=svn167&r=167
Code Snip: (I have converted chines string into standard English)
public class TimeLineActivity extends ListActivity {
private TwitterPreferenceManager tpm = new TwitterPreferenceManager(this);
private static final int FOLLOW = 1;
private static final CharSequence FOLLOW_LABEL = "Follow";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// timeline Obtaining process
String screenName = getIntent().getStringExtra("screen_name");
List<String> list = this.getTimeLine(screenName);
setListAdapter(new ArrayAdapter<String>(this, R.layout.timeline_item,list));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, FOLLOW, 0, FOLLOW_LABEL);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case FOLLOW:
ConfigurationBuilder builder = new ConfigurationBuilder();
Configuration conf = builder.setOAuthAccessToken(tpm.getAccessToken())
.setOAuthAccessTokenSecret(tpm.getAccessTokenSercret())
.setOAuthConsumerKey(TwitterPreferenceManager.CONSUMER_KEY)
.setOAuthConsumerSecret(TwitterPreferenceManager.CONSUMER_SERCRET)
.setDebugEnabled(true)
.build();
Twitter twitter = new TwitterFactory(conf).getInstance();
try {
String screen_name = getIntent().getStringExtra("screen_name");
twitter.createFriendship(screen_name);
Toast.makeText(getApplicationContext(), "Was to follow.", Toast.LENGTH_LONG).show();
} catch (TwitterException e) {
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
e.printStackTrace();
}
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
/**
* Get the time line for the specified user
*
* #param screenName
* #return
*/
private List<String> getTimeLine(String screenName) {
List<String> result = new ArrayList<String>();
Twitter twitter = new TwitterFactory().getInstance();
ResponseList<Status> userTimeline;
try {
userTimeline = twitter.getUserTimeline(screenName);
for (Status status : userTimeline) {
result.add(status.getText());
}
} catch (TwitterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}
}
iPhone
http://www.chrismaddern.com/twitter-follow-button-for-ios-iphone-code/
Here is the way, How todo
The FollowMeButton can be created in Interface Builder by adding a UIButton and changing it's class to FollowMeButton or in code using the custom initialiser:
[self.view addSubview:[[FollowMeButton alloc] initWithTwitterAccount:#"chrismaddern" atOrigin:CGPointMake(205, 248) isSmallButton:YES]];
Two size modes are available controlled by setting isSmallButton in the initialiser or by later change the isSmall property of the object.