Error Sending twilio SMS via parse - objective-c

I'm trying to send a text message via Twilio and parse, but the cloud function produces "uh oh something went wrong." why?
Here's the xcode code:
//Sends SMS via Parse Cloud code to a number....//TODO test, debug...
+(void)sendSMSWithVerificationCode:(NSString *)verificationString toNumberString:(NSString *)phoneNumber {
NSMutableString * message=[[NSMutableString alloc] initWithString:#"Brighten verification code: "];
[message appendString:verificationString];
// Call our Cloud Function that sends an SMS with Twilio
[PFCloud callFunctionInBackground:#"sendSMSVerification"
withParameters:#{ #"number" : phoneNumber , #"messageString" : message}
block:^(id object, NSError *error) {
[[[UIAlertView alloc] initWithTitle:#"Verification code sent!"
message:nil
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil] show];
}];
}
and the cloud function looks as follows:
twilio.initialize("meh",",mehh"); //these are for testing; todo insert real ones when deploying
// Create the Cloud Function
Parse.Cloud.define("sendSMSVerification", function(request, response) {
// Use the Twilio Cloud Module to send an SMS
twilio.sendSMS({
From: "111111111111111(my number as a string)",
To: request.params.number,
Body: request.params.message //SMS Verification: 1234 or whatever the specific number is...
}, {
success: function(httpResponse) { response.success("SMS sent!"); },
error: function(httpResponse) { response.error("Uh oh, something went wrong"); }
});
});

Related

Get list of online users PubNub always nil Objective C

My question is same of User list for pubnub-chat objective c but it seem has no helpful answers.
I registed client with Pub & Sub key with Presence = YES
I subsrcibed to "My channel" and could send msg to it
I used debug console in PubNub admin to create 2 others clients, I could send msg together
I enable Presence in Admin (http://prntscr.com/iyv7b1)
I get list user that subscribe "My channel" by function:
[client hereNowForChannel:#"My channel" withVerbosity:PNHereNowState completion:^(PNPresenceChannelHereNowResult *result, PNErrorStatus *status)
{
if (!status) {
}
else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Couldn't get list of user." delegate:nil cancelButtonTitle:#"Close" otherButtonTitles:nil];
[alert show];
}
}];
I tried to change
PNHereNowState -> PNHereNowUUID -> PNHereNowOccupancy
But my result is always NIL.
Anybode help me, pls
I found the answer for my question, hope it helps for who need
[client hereNowForChannel:client.globalChannel withCompletion:^(PNPresenceChannelHereNowResult *result, PNErrorStatus *status)
{
if (!status) {
PNPresenceChannelHereNowData *data = result.data;
if (data) {
NSArray *list = [data uuids];
}
}
else {
}
}];
The property data, it won't be set value if has no access to it yet, so I did call PNPresenceChannelHereNowData *data = result.data; and it had data.

Objective-C Firebase reloadWithCompletion not executing completion code

My code is not executing the completion callback after calling reloadWithCompletion
if ([FIRAuth auth].currentUser.isEmailVerified) {
_emailField.text = [FIRAuth auth].currentUser.email;
} else {
[[FIRAuth auth].currentUser reloadWithCompletion:^(NSError * _Nullable error) {
if ([FIRAuth auth].currentUser.isEmailVerified) {
_emailField.text = [FIRAuth auth].currentUser.email;
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Email Validation"
message:#"Your email must be validated to continue."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
}];
}
Any help is appreciated.
As it turns out I fixed the problem but I still don't know why or how the completion code was not working for this user. I simply used the Firebase Authentication console to delete the user record. My app then re-created the record and now the completion code executes properly.

react-native logInWithReadPermissions not calling safari sometimes, no error thrown, handle (callback) not called

I am using FBSDKLoginManager to log in with facebook manually.
I have created a native method in which I have the following code:
#import "FacebookLoginManager.h"
#import "FBSDKCoreKit/FBSDKCoreKit.h"
#import "FBSDKLoginKit/FBSDKLoginKit.h"
#implementation FacebookLoginManager
RCT_EXPORT_MODULE();
RCT_EXPORT_METHOD(newSession:(RCTResponseSenderBlock)callback) {
dispatch_async(dispatch_get_main_queue(), ^{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"public_profile", #"email"] fromViewController: nil handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
callback(#[#"Error", [NSNull null]]);
} else if (result.isCancelled) {
callback(#[#"Canceled", [NSNull null]]);
} else {
FBSDKAccessToken *token = result.token;
NSString *tokenString = token.tokenString;
NSString *userId = token.userID;
NSDictionary *credentials = #{ #"token" : tokenString, #"userId" : userId };
callback(#[[NSNull null], credentials]);
}
}];
});
};
The code works mostly but sometimes it does not trigger the login window (safari) although it does not throw any error.
Besides, the handler code is never called in this case. If I close the app and reopen it everything works again.
The problem happens after a period of time passes so I suspect it may be related to some timeout or token expiration somewhere but I am not sure.
How can I fix this problem, any idea?
I realized that revoking the facebook access token on logout solved the problem. Perhaps the FBSDKLoginManager had some problems when the user had already authorized your app and you try to ask for authorization again.
To revoke the token I make a remote call to my server which has facebook's PHP SDK:
<?php
$fb = new Facebook(array(
'app_id' => 'YOUR_FB_APP_ID',
'app_secret' => 'YOUR_FB_APP_SECRET',
'default_graph_version' => 'v2.5',
));
try
{
$userFbToken = 'user-fb-token-stored-somewhere';
$appsecret_proof = hash_hmac('sha256', $userFbToken, 'YOUR_FB_APP_SECRET');
$response = $fb->delete("/me/permissions", array('appsecret_proof'=>$appsecret_proof),$userFbToken);
}
catch(FacebookResponseException $e)
{
// exception handling...
}

Twitter OAuth and accessToken to GET statuses/user_timeline in Objective-C

I'm trying to acquire the accessToken value from Twitter for using it in my app (I need to use API v1.1's Authentication Model for GET statuses/user_timeline); I have registered my app on api.twitter.com, imported the AFOAuth1Client classes in the project, and this is the simple code:
- (void)viewDidLoad
{
self.twitterClient = [[AFOAuth1Client alloc] initWithBaseURL:
[NSURL URLWithString:#"https://api.twitter.com/"] key:#"MYKEY" secret:#"MYSECRETKEY"];
AFOAuth1Token *accessToken;
[self.twitterClient acquireOAuthAccessTokenWithPath:#"oauth/request_token" requestToken:accessToken accessMethod:#"GET" success:^(AFOAuth1Token *accessToken) { // I have tried also accessMethod: #"POST"
NSLog(#"Success: %#", accessToken);
} failure:^(NSError *error) {
NSLog(#"Error: %#", error);
}];
}
Unluckly XCode give me this error:
Error: Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 401" UserInfo=0x79a14f0 {NSLocalizedRecoverySuggestion=Failed to validate oauth signature and token, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x7956390>
What is wrong here? DO i need to REGISTER app on api.twitter.com? Is it the right way, or, what is the simpler way to Get statuses/user_timeline using API v1.1's Twitter Authentication Model in iOS? Thank you!
EDIT: possible waypoint?
1) register a new app on dev.twitter.com
2) in OAuth settings, read Consumer key and Consumer secret
3) set default app access type to read? or read/write? ask for access tokens? use this values in.... ?
It's been a few days since Twitter added an application only mode. In this mode, you can access specific API endpoints without user's context, ie. your users don't have to authenticate. Only the application does authenticate once in a while to get a "bearer token" which is then sent in every request.
The following code gets a bearer token and then retrieves the public timeline for #barackobama.
STTwitterAPI *twitter = [STTwitterAPI twitterAPIApplicationOnlyWithConsumerKey:#""
consumerSecret:#""];
[twitter verifyCredentialsWithSuccessBlock:^(NSString *bearerToken) {
NSLog(#"Access granted with %#", bearerToken);
[twitter getUserTimelineWithScreenName:#"barackobama" successBlock:^(NSArray *statuses) {
NSLog(#"-- statuses: %#", statuses);
} errorBlock:^(NSError *error) {
NSLog(#"-- error: %#", error);
}];
} errorBlock:^(NSError *error) {
NSLog(#"-- error %#", error);
}];
See STTwitter iOS demo project for a working example (use you own consumer key / secret).
If you have your own consumer tokens, you can use the STTwitter library I wrote.
STTwitterAPI *twitter =
[STTwitterAPI twitterAPIWithOAuthConsumerName:#""
consumerKey:#"your_key"
consumerSecret:#"your_secret"
username:#"username"
password:#"password"];
[twitter verifyCredentialsWithSuccessBlock:^(NSString *username) {
NSLog(#"Access granted for %#", username);
[twitter getUserTimelineWithScreenName:#"barackobama"
successBlock:^(NSArray *statuses) {
NSLog(#"-- statuses: %#", statuses);
} errorBlock:^(NSError *error) {
NSLog(#"-- error: %#", error);
}];
} errorBlock:^(NSError *error) {
NSLog(#"-- error %#", error);
}];
If your tokens are not 'xAuth' enabled, you'll have to use a PIN. STTwitter provides simple asynchronous block-based methods to ask the user. You can also choose to automate the PIN retrieval, see STTwitterDemo -[AppDelegate guessPIN:] for an automated process.
STTwitter is simple for use . Also I added example that you can get public twitter timeline

How to change video from private to public YouTube API with Gdata for iOS App

I have an iOS app that gets all the videos from a user through gdata and YouTube API. My problem comes with private videos, I need to make it so that it makes a private video public when the video is selected.
For some reason whenever I try to make the video public, I cannot edit it because the editLink of an entry returned by YouTube API is empty.
Here's my code someone can tell me what I'm doing wrong or what I can do to make the change:
GDataEntryBase *entry = [[feed entries] objectAtIndex:selectedRow];
[[(GDataEntryYouTubeVideo *)entry mediaGroup] setIsPrivate:NO];
//GDataEntryYouTubeUpload *uploadEntry =
//[GDataEntryYouTubeUpload uploadEntryWithMediaGroup:mediaGroup
//fileHandle:nil MIMEType:#"video/mp4" slug:[[entry title]
//stringValue]];
GDataServiceTicket *ticket;
GDataServiceGoogleYouTube *service = [self youTubeService];
NSString *str = [entry canEdit] ? #"YES" : #"NO";
NSLog(#"Can edit %#", str);
NSLog(#"Edit URL %#", [[entry editLink] URL] );
// NSURL *url = [GDataServiceGoogleYouTube
//youTubeUploadURLForUserID:kGDataServiceDefaultUser];
ticket = [service fetchEntryByUpdatingEntry:entry
forEntryURL:[[entry editLink] URL] delegate:self
didFinishSelector:#selector(uploadTicket:finishedWithEntry:error:)];
// ticket = [service fetchEntryByUpdatingEntry:entry
//delegate:self didFinishSelector:#selector(uploadTicket:finishedWithEntry:error:)];
NSLog(#"Ticket = %#", ticket);
}
}
- (void)uploadTicket:(GDataServiceTicket *)ticket
finishedWithEntry:(GDataEntryYouTubeVideo *)videoEntry error:(NSError
*)error {
NSLog(#"Finished...");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Upload
failed" message:[NSString stringWithFormat:#"Upload failed: %#",
error] delegate:self cancelButtonTitle:#"Cancel"
otherButtonTitles:nil, nil];
if (error != nil) {
NSLog(#"Errors: %#", error);
[alert show];
} else {
NSLog(#"NO ERRORS :))");
}
}
I included developer key in the request/response shown below and received the editLink in the response. You will have to relate the protocol using the oauth playground to your client-side language.
https://groups.google.com/group/youtube-api-gdata/browse_thread/thread/346eb7c8bdd6c3ae
Did you authenticate your requests?
Did you specify v=2?
Did you include the developer key in the query?
If your authenticated and using v=2 in the query string then you should get the edit link.
Learn the dev tools at https://code.google.com/oauthplayground/ where i made the following request specifying partial gdata fields that would contain just the link[#rel="edit"] tag :
GET /feeds/api/users/default/uploads/7dtC4kS3x08?v=2&fields=link%5B%40rel%3D%22edit%22%5D&alt=json&key=${YT-devKeyValue} HTTP/1.1
Host: gdata.youtube.com
Authorization: OAuth ya29.AHES6ZSqIlhsyFfbzZ7x-PTVR1JiTj1PjPvBbfq7RtKnaJk
Response includes editlink at the bottom - you should use the value of the attribute=href when you POST your update to the api:
{
"version":"1.0",
"encoding":"UTF-8",
"entry":{
"xmlns":"http://www.w3.org/2005/Atom",
"xmlns$yt":"http://gdata.youtube.com/schemas/2007",
"link":[
{
"rel":"edit",
"type":"application/atom+xml",
"href":"https://gdata.youtube.com/feeds/api/users/rowntreerob/uploads/7dtC4kS3x08?v=2"
}
]
}
}