NSURLERRORDOMAIN--1012E: (null) on Bluemix - ios

I am trying to connect Bluemix remote DB as the following:
IMFDataManager.sharedInstance().remoteStore("people", completionHandler: { (store:CDTStore!, error:NSError!) -> Void in
var query:CDTCloudantQuery = CDTCloudantQuery(dataType: "Person")
store.performQuery(query, completionHandler: { (results:[AnyObject]!, error:NSError!) -> Void in
var myData = results as! [Person]
println(myData.count)
})
})
For some reason I get the following error message.
I have checked the documentation and couldn't find any relevant about authentication.
2015-06-01 19:05:38.672 helloBluemix[34398:2621801] [INFO] [IMFData] Authorization failure. Http status 401 received on request to https://mobile.ng.bluemix.net/imfdata/api/v1/apps/5fc5cfd9-73db-432b-a1f5-3f2824e1c5ec/peoples/_find
2015-06-01 19:05:38.676 helloBluemix[34398:2621799] [ERROR] [IMFData] Error occured during query. URL: https://mobile.ng.bluemix.net/imfdata/api/v1/apps/5fc5cfd9-73db-432b-a1f5-3f2824e1c5ec/peoples/_find. queryJSON: {
selector = {
"#datatype" = Person;
};
} NSURLERRORDOMAIN--1012E: (null)

Same problem here.
I did some changes to my code but could not think of something I changed in the Bluemix interaction code...
When I previously had authorization errors I was able to fix it by adjusting the access rights for the database in the "Cloudant Dashboard". However, it is now set to "Read" and "Write" for "Everybody else", so that should not be an issue.

I was getting the same error before I set user permissions on my IMFDataManager object after I got a reference to it:
IMFDataManager *manager = [IMFDataManager sharedInstance];
[manager remoteStore:#"<your_db_name>" completionHandler:^(CDTStore *store, NSError *error) {
if (error) {
NSLog(#"there was an error fetching or creating the remote store");
} else {
NSLog(#"remote store success");
[manager setCurrentUserPermissions:DB_ACCESS_GROUP_MEMBERS forStoreName:#"<your_db_name>" completionHander:^(BOOL success, NSError *error) {
if (error) {
NSLog(#"error setting permissions");
} else {
NSLog(#"set permissions successfully");
}
}];
}
}];

Related

iOS Quickblox error: Request failed: unauthorized (401)

I have been working on quickblox framework integration. I follow https://quickblox.com/developers/IOS link for integration, but unfortunately I stop at signup user step
Signup code
QBUUser *user=[[QBUUser alloc] init];
user.login=#"abc";
user.password=#"12345678";
[QBRequest signUp:user successBlock:^(QBResponse * _Nonnull response, QBUUser * _Nonnull tUser) {
NSLog(#"Successfully signup:-%#",tUser);
} errorBlock:^(QBResponse * _Nonnull response) {
NSLog(#"Error in signup:- %#",response);
}];
Every time it will return
error: Request failed: unauthorized (401)
reasons: {
errors = {
base = (
"Required session does not exist"
);
};
}
How can I resolve this?
Here is working code for (Swift 4)
let user = QBUUser()
user.login = "abc"
user.password = "12345678"
QBRequest.signUp(user, successBlock: { response, tUser in
print("Successfully signup:-\(tUser)")
}, errorBlock: { response in
print("Error in signup:- \(response)")
})
Output :

Unable to localize Face Id popup for non-matching face

It seems like Face Id is ignoring localizedFallbackTitle and localizedReason. However localizedCancelTitle is working fine. Does anyone know how to get it work?
My code:
LAContext *context = [[LAContext alloc] init];
if ([context respondsToSelector:#selector(setLocalizedCancelTitle:)]) {
context.localizedCancelTitle = [Language get:CANCEL alter:nil];
}
if ([context respondsToSelector:#selector(setLocalizedFallbackTitle:)])
{
context.localizedFallbackTitle = [Language get:TRY_AGAIN alter:nil];
}
NSError *error = nil;
if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthentication error:&error]) {
[context evaluatePolicy:LAPolicyDeviceOwnerAuthentication
localizedReason:[Language get:AUTHRNTICATE_USING_YOUR_FACE alter:nil] reply:^(BOOL success, NSError *error) {
//code
}
Screenshot:
I want to localize everything on this popup if possible.
Note: Attached screenshot is taken on simulator. I have also checked
it on real device but the result is same. Also, for Touch id it is working properly.
According to this Post, there is no API for changing the Reason in between the auth process.
localizedReason
The app-provided reason for requesting authentication, which displays in > the authentication dialog presented to the user.
You can use BiometricAuthentication to show your message.
BioMetricAuthenticator.authenticateWithBioMetrics(reason: "", success: {
// authentication successful
}, failure: { [weak self] (error) in
// do nothing on canceled
if error == .canceledByUser || error == .canceledBySystem {
return
}
// device does not support biometric (face id or touch id) authentication
else if error == .biometryNotAvailable {
self?.showErrorAlert(message: error.message())
}
// show alternatives on fallback button clicked
else if error == .fallback {
// here we're entering username and password
self?.txtUsername.becomeFirstResponder()
}
// No biometry enrolled in this device, ask user to register fingerprint or face
else if error == .biometryNotEnrolled {
self?.showGotoSettingsAlert(message: error.message())
}
// Biometry is locked out now, because there were too many failed attempts.
// Need to enter device passcode to unlock.
else if error == .biometryLockedout {
// show passcode authentication
}
// show error on authentication failed
else {
self?.showErrorAlert(message: error.message())
}
})

hypertrack - always show Device disconnected on dashboard objective c iOS

i am creating action "visit" after new user create in objective c iOS but on dashboard device disconnected show against user nor can see location through url or action id. here is screen short.
-(void)createUser{
[HyperTrack initialize:#"......."];
[HyperTrack requestAlwaysAuthorizationWithCompletionHandler:^(BOOL authorized) {
//handle authorization status, if needed
}];
[HyperTrack requestMotionAuthorization];
[HyperTrack getOrCreateUser:#"test1" _phone:#"12345" :#"12" completionHandler:^(HyperTrackUser * _Nullable user, HyperTrackError * _Nullable error) {
if (user) {
// Handle getOrCreateUser API success here
NSLog(#"User Created");
NSLog(#"%#",user.id);
[self createAction:user.id];
} else {
// Handle createUser error here, if required
NSLog(#"User Created error %#",error);
}
}];
}
-(void)createAction:(NSString *)userId{
HyperTrackActionParams* actionParams = [[HyperTrackActionParams alloc] init];
[actionParams setType:#"visit"];
[actionParams setUserId:userId];
[HyperTrack createAndAssignAction:actionParams :^(HyperTrackAction * action, HyperTrackError * error) {
if (error) {
// Handle createAction API error here
return;
}
if (action) {
// Handle createAction API success here
NSLog(#"%#",action.id);
NSLog(#"%#",action.trackingUrl);
}
}];
}
My pod was outdated. I reinstalled pod with pod 'HyperTrack', '~> 0.7'. Now its working fine.

How to get user email address via Twitter API in iOS?

I have tried multiple SDK's but was unable to get an email ID from any of the resources. I have tried FHSTwitterEngine for this purpose but I didn't get the solution.
FHSTwitterEngine *twitterEngine = [FHSTwitterEngine sharedEngine];
NSString *username = [twitterEngine loggedInUsername]; //self.engine.loggedInUsername;
NSString *key = [twitterEngine accessToken].key;
NSString *secrete = [twitterEngine accessToken].secret;
if (username.length > 0)
{
NSDictionary *userProfile = [[FHSTwitterEngine sharedEngine] getProfileUsername:username];
NSLog(#"userProfile: %#", userProfile);
EDIT
After Twitter has updated APIs, Now user can get Email using TWTRShareEmailViewController class.
// Objective-C
if ([[Twitter sharedInstance] session]) {
TWTRShareEmailViewController* shareEmailViewController = [[TWTRShareEmailViewController alloc] initWithCompletion:^(NSString* email, NSError* error) {
NSLog(#"Email %#, Error: %#", email, error);
}];
[self presentViewController:shareEmailViewController animated:YES completion:nil];
} else {
// TODO: Handle user not signed in (e.g. attempt to log in or show an alert)
}
// Swift
if Twitter.sharedInstance().session {
let shareEmailViewController = TWTRShareEmailViewController() { email, error in
println("Email \(email), Error: \(error)")
}
self.presentViewController(shareEmailViewController, animated: true, completion: nil)
} else {
// TODO: Handle user not signed in (e.g. attempt to log in or show an alert)
}
NOTES:
Even if the user grants access to her email address, it is not guaranteed you will get an email address. For example, if someone signed up for Twitter with a phone number instead of an email address, the email field may be empty. When this happens, the completion block will pass an error because there is no email address available.
Twitter Dev Ref
PAST
There is NO way you can get email address of a twitter user.
The Twitter API does not provide the user's email address as part of the OAuth token negotiation process nor does it offer other means to obtain it.
Twitter Doc.
You will have to use Twitter framework. Twitter has provided a beautiful framework for that, you just have to integrate it in your app.
To get user email address, your application should be whitelisted. Here is the link. Go to use this form. You can either send mail to sdk-feedback#twitter.com with some details about your App like Consumer key, App Store link of an App, Link to privacy policy, Metadata, Instructions on how to log into our App etc..They will respond within 2-3 working days.
Here is the story how I got whitelisted by conversation with Twitter support team:
Send mail to sdk-feedback#twitter.com with some details about your App like Consumer key, App Store link of an App, Link to privacy policy, Metadata, Instructions on how to log into our App. Mention in mail that you want to access user email adress inside your App.
They will review your App and reply to you withing 2-3 business days.
Once they say that your App is whitelisted, update your App's settings in Twitter Developer portal. Sign in to apps.twitter.com and:
On the 'Settings' tab, add a terms of service and privacy policy URL
On the 'Permissions' tab, change your token's scope to request email. This option will only been seen, once your App gets whitelisted.
Put your hands on code
Use of Twitter framework:
Get user email address
-(void)requestUserEmail
{
if ([[Twitter sharedInstance] session]) {
TWTRShareEmailViewController *shareEmailViewController =
[[TWTRShareEmailViewController alloc]
initWithCompletion:^(NSString *email, NSError *error) {
NSLog(#"Email %# | Error: %#", email, error);
}];
[self presentViewController:shareEmailViewController
animated:YES
completion:nil];
} else {
// Handle user not signed in (e.g. attempt to log in or show an alert)
}
}
Get user profile
-(void)usersShow:(NSString *)userID
{
NSString *statusesShowEndpoint = #"https://api.twitter.com/1.1/users/show.json";
NSDictionary *params = #{#"user_id": userID};
NSError *clientError;
NSURLRequest *request = [[[Twitter sharedInstance] APIClient]
URLRequestWithMethod:#"GET"
URL:statusesShowEndpoint
parameters:params
error:&clientError];
if (request) {
[[[Twitter sharedInstance] APIClient]
sendTwitterRequest:request
completion:^(NSURLResponse *response,
NSData *data,
NSError *connectionError) {
if (data) {
// handle the response data e.g.
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:data
options:0
error:&jsonError];
NSLog(#"%#",[json description]);
}
else {
NSLog(#"Error code: %ld | Error description: %#", (long)[connectionError code], [connectionError localizedDescription]);
}
}];
}
else {
NSLog(#"Error: %#", clientError);
}
}
Hope it helps !!!
If you'd like a user's email address, you'll need to ask a user for it within the confines of your own application and service. The Twitter API does not provide the user's email address as part of the OAuth token negotiation process nor does it offer other means to obtain it.
In Swift 4.2 and Xcode 10.1
It's getting email also.
import TwitterKit
#IBAction func onClickTwitterSignin(_ sender: UIButton) {
TWTRTwitter.sharedInstance().logIn { (session, error) in
if (session != nil) {
let name = session?.userName ?? ""
print(name)
print(session?.userID ?? "")
print(session?.authToken ?? "")
print(session?.authTokenSecret ?? "")
let client = TWTRAPIClient.withCurrentUser()
client.requestEmail { email, error in
if (email != nil) {
let recivedEmailID = email ?? ""
print(recivedEmailID)
}else {
print("error--: \(String(describing: error?.localizedDescription))");
}
}
let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
self.navigationController?.pushViewController(storyboard, animated: true)
}else {
print("error: \(String(describing: error?.localizedDescription))");
}
}
}
Swift 3-4
#IBAction func btnTwitterAction(_ sender: Any) {
TWTRTwitter.sharedInstance().logIn(completion: { (session, error) in
if (session != nil) {
print("signed in as \(String(describing: session?.userName))");
if let mySession = session{
let client = TWTRAPIClient.withCurrentUser()
//To get User name and email
client.requestEmail { email, error in
if (email != nil) {
print("signed in as \(String(describing: session?.userName))");
let firstName = session?.userName ?? "" // received first name
let lastName = session?.userName ?? "" // received last name
let recivedEmailID = email ?? "" // received email
}else {
print("error: \(String(describing: error?.localizedDescription))");
}
}
//To get user profile picture
client.loadUser(withID: session?.userID, completion: { (userData, error) in
if (userData != nil) {
let fullName = userData.name //Full Name
let userProfileImage = userData.profileImageLargeURL //User Profile Image
let userTwitterProfileUrl = userData?.profileURL // User TwitterProfileUrl
}
})
}
} else {
print("error: \(error?.localizedDescription)");
}
})
}

Fetching Current User Profile using Objective C Google Plus Client Library

I am using the Google CLient Libraries for Objective C available here..
I have successfully been able to Authorize the user and get refresh token. (Using the GTMOAuthenticaion api embedded within).
In the Selector called after successful authorization I make the Get User Profile request as follows.. (I need the id of currently loggedin/authenticated user)
-(void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
if (error != nil) {
NSLog(#"Stop");
} else {
if ([auth canAuthorize]){
[Mediator plusService].authorizer = auth;
// Problematic Line
GTLQueryPlus *profileQuery = [GTLQueryPlus queryForPeopleGetWithUserId:#"me"]; // Notice the UserId Param
profileQuery.completionBlock = ^(GTLServiceTicket *ticket, id object, NSError *error) {
if (error == nil) {
self.mediator.gProfile = object;
} else {
NSLog(#"GPlus Service Error %#", error);
}
};
[[Mediator plusService] executeQuery:profileQuery completionHandler:
^(GTLServiceTicket *ticket, id result, NSError *error) {
if (error)
NSLog(#"Some Service Error %#", error);
}];
}
}
}
If I put "me" as parameter, I get invalid user ID error string in jSON response.
However, If I provide some userId like my own 113632923069489732066 it works perfectly fine and returns the appropriate jSON response..!!
The Example for Google Plus inside Examples folder also fails to get current user profile ending with following error.
Error Domain=com.google.GTLJSONRPCErrorDomain Code=400 "The operation couldn’t be completed. (Invalid user ID: {0})" UserInfo=0x7a670fa0 {NSLocalizedFailureReason=(Invalid user ID: {0}), GTLStructuredError=GTLErrorObject 0x7a67b130: {message:"Invalid user ID: {0}" code:400 data:[2]}, error=Invalid user ID: {0}}
P.S. My API Console application doesn't work with iOS option under installed app but needs be configured with "Other" option. When configured with iOS option, the oAuth fails with invalid_client error response.
My Mistake .. !! And a very silly one .. !!
I was signing in using a Gmail Account that was yet not associated with GPlus .. !! =/

Resources