Facebook Pages API Swift - ios

I'm new in programming in swift. I'm trying to read Facebook pages posts(wall) from a public page and show the content(images and messages) in my app without users login. I've already set up the app with Facebook SDK (plist, bridging-Header.h etc...). I know I must open a session and pass a valid access token to the Facebook server. But I can't understand how....
below my viewDidLoad
let request = "/(pageID)?fields=id,posts"
FBRequestConnection.startWithGraphPath(request, completionHandler: {(connection: FBRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
if (error? != nil){
NSLog("error = \(error)")
}else{
println(result)
}
} as FBRequestHandler)
I get this error:
An open FBSession must be specified for calls to this endpoint.
com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 104;
message = "An access token is required to request this resource.";
type = OAuthException;
};
};
code = 400;
}}
i think i need to open a session in AppDelegate and so I can make the request I've also read the Facebook documentation but I haven't found the answer.
Please help me. Thank you!!!

Related

FBSDK OAuth error on Xcode, Swift - Graph API for app id "New App ID" called, but token has app id "old app ID"

Facebook OAuth error switching from one app ID to another
I worked with contract devs who created the iOS application on another Facebook app ID which i can't control. I am trying to switch it to mine but ran into an error that the token still is using the old App ID. I switched the AppID & the CFBundleURLSchemes in the Plist too. The app compiles with no errors & I am able to get through to FB OAuth but once I sign in, it doesn't go through.
This is the error that I'm receiving
2019-11-15 17:13:20.233275-0600 Imbue[28564:6158269] FBSDKLog: Failed to send AppEvents: Error Domain=com.facebook.sdk.core Code=8 "(null)" UserInfo={com.facebook.sdk:FBSDKGraphRequestErrorHTTPStatusCodeKey=400, com.facebook.sdk:FBSDKErrorDeveloperMessageKey=(#100) Graph API for app id 472586343541363 called, but token has app id 2470569892995934, com.facebook.sdk:FBSDKGraphRequestErrorParsedJSONResponseKey={
body = {
error = {
code = 100;
"fbtrace_id" = "AknZ_YjiTwxrvivhd6v2f_d";
message = "(#100) Graph API for app id 472586343541363 called, but token has app id 2470569892995934";
type = OAuthException;
};
};
code = 400;
(#100) Graph API for app id 472586343541363 called, but token has app id 2470569892995934,
This is the code I have for OAuth
#objc private func authenticateWithFacebook() {
LoginManager().logIn(permissions: ["email", "public_profile"], from: self) { [weak self] (result, err) in
guard let authResult = result else { self?.show(message: FailureMessage.Login.message); return }
if err != nil || authResult.isCancelled {
self?.show(message: FailureMessage.Login.message)
}else {
self?.presentProtectedPage()
}
}
}
I'm not sure what the issue is, have been wrestling with it all day & I feel like it's something super simple. Would appreciate your help as a newbie to swift.
Thanks!

linkedin get profile - Request failed: forbidden (403) error swift

I am facing problem with "https://api.linkedin.com/v2/me" api of LinkedIn. Code was working good when I was using v1 api. I have updated my code for version 2 api for linkedIn authentication and When I tried to get profile with api "https://api.linkedin.com/v2/me" I am getting error Request failed: forbidden (403). I don't know how to resolve it.
Here is my code:
let linkedinHelper = LinkedinSwiftHelper(configuration: LinkedinSwiftConfiguration(clientId: Constant.Key.kLinkedInClientId, clientSecret: Constant.Key.kLinkedInClientSecret, state: Constant.Key.kLinkedInState, permissions: ["r_basicprofile", "r_emailaddress"], redirectUrl: Constant.Key.kLinkedInRedirectURL),nativeAppChecker: WebLoginOnly())
linkedinHelper.authorizeSuccess({ (token) in
print(token)
let url = "https://api.linkedin.com/v2/me"
linkedinHelper.requestURL(url, requestType: LinkedinSwiftRequestGet, success: { (response) -> Void in
print(response)
}) {(error) -> Void in
print(error.localizedDescription)
//handle the error
}
I've set URL scheme in info.plist as well.
You have to pass key in oauth2_access_token
Example:
https://api.linkedin.com/v2/me?oauth2_access_token={linkedin_key}
Edit:-
Also in permission need to set "r_liteprofile" instead of "r_basicprofile". To change permission worked for me.

How do I get to AccessToken and IdToken following successful Amazon Cognito Login from iOS

I have been using the following sample to introduce cognito login to my iOS application:
https://github.com/awslabs/aws-sdk-ios-samples/tree/master/CognitoYourUserPools-Sample
This is working well and I am at the point where I have a AWSCognitoIdentityUserPool object which I can call the currentUser() method to access the user.
What I am struggling to find is how I extract both the AccessToken and the IdToken.
In the android equivalent, the onSuccess method of the AuthenticationHandler has a CognitoUserSession argument which in turn has getIdToken() and getAccessToken().
Frustratingly, I see them output as the AuthenticationResult in json format in the output window, but I just don't know how to access them programatically?
Figured it out now:
func getSession(){
self.user?.getSession().continueOnSuccessWith { (getSessionTask) -> AnyObject? in
DispatchQueue.main.async(execute: {
let getSessionResult = getSessionTask.result
self.idToken = getSessionResult?.idToken?.tokenString
self.accessToken = getSessionResult?.accessToken?.tokenString
})
return nil
}
}

How to authenticated Google Cloud Endpoint call from an iOS client

My google backend APIs are using Oauth 2.0, when i call one of my api with that code :
func userService() -> GTLServiceUserController{
var service : GTLServiceUserController? = nil
if service == nil {
service = GTLServiceUserController()
service?.retryEnabled = true
}
return service!
}
And
func callApi() {
let service = userService()
let query = GTLQueryUserController.queryForGetAllUsers()
service.executeQuery(query) { (ticket: GTLServiceTicket!, object: AnyObject!, error: NSError!) -> Void in
if(error != nil){
print("Error :\(error.localizedDescription)")
return
}
let resp = object as? GTLUserControllerOperationResponse
if(resp != nil){
print(resp)
}
}
}
I'm getting The operation couldn’t be completed. (com.google.appengine.api.oauth.OAuthRequestException: unauthorized)
I already read this article, but i don't want my users to log in, instead i want my app to present its credentials to the service for authentication without user interaction.
I want to use this approach, but they are not telling how to do it with iOS apps.
So basically i want to be able to call my APIs successfully without any user interaction or sign-in dialog.
Please note that i have those classes on my project :
GTMOAuth2Authentication
GTMOAuth2SignIn
GTMOAuth2ViewControllerTouch
Thank's in advance
If you don't need to authenticate individual users (via OAuth2 login), then you do not need to do anything else and your App can directly call the API (as described in the "Calling the Endpoint API (unauthenticated)" section).
Service accounts are for server-to-server interactions and cannot be used to authenticate individual users; if you embed a service account & key within your iOS App, anyone can extract it from the App and start calling your API, hence it does not add any security.

sending accessToken to server using swift ios

I am trying to use facebook ios login sdk. I get the access Token using below code. Now i want to send this token to a server so that server can validate this token by making a call to facebook server.
I am using the below code to get the accessToken , i am using swift in ios 8.
var accessToken = FBSession.activeSession().accessTokenData
When i am trying to send this token to server getting an error saying that type of accessToken is not convertible to NSString.
Please help me where i am wrong.
First, make sure that you have an open session. I use this approach in my AppDelegate:
FBSession.openActiveSessionWithAllowLoginUI(false)
Second, you can get accessToken as a string from accessTokenData:
var myToken = FBSession.activeSession().accessTokenData.accessToken
From there, you can send it to your server however you want. I tried a couple request wrappers until I settled on Net. Getting your token to your server is pretty easy if you have a library like Net so that you don't have to handle the low level network request interfaces:
func doLogin() -> Void {
let net = Net(baseUrlString: "http://myhost.com/")
let url = "auth/facebook_access_token"
let params = ["access_token": myToken]
net.GET(url, params: params, successHandler: { responseData in
let result = responseData.json(error: nil)
// Do something with whatever you got back
NSLog("result \(result)")
}, failureHandler: { error in
NSLog("Error")
})
}
Good luck! I hope I was able to help!

Resources