Fetching data from Facebook page's events page - ios

I would like to pull data from a Facebook event page that would fetch all the events listed by a Facebook page. I have to up the iOS SDK, but i am now unsure how to call the Graph API. I found the PAGE ID for a Facebook group page i want to take the events from by looking at the page's source code and finding "PAGEID".
I have set it up all in my dashboard along with my Bundle ID. The only left is to call the Graph API, but i am unsure and left confused when trying to following their doc.

Show us the code you tried already and what is not working.
Have you tried this already? (where {page-id} is your page's ID):
let connection = GraphRequestConnection()
connection.add(GraphRequest(graphPath: "/{page-id}/events")) { httpResponse, result in
switch result {
case .success(let response):
print("Graph Request Succeeded: \(response)")
case .failed(let error):
print("Graph Request Failed: \(error)")
}
}
connection.start()

Related

iOS: ScreenTime API FamilyControl Autorization failed

I am trying to implement the Screentime app and I have added the Family Controls capability to my sample app. But, I'm getting a FamilyControlsError Code=0 when requesting authorization from an iPad OS v15.7.1 signed in with a child iCloud account.
I am using below code:
AuthorizationCenter.shared.requestAuthorization { result in
switch result {
case .success():
print("Sucess...")
case .failure(let error):
print("Failed... \(error)")
}
}
Please let me know if I am missing anything.

AWS Amplify iOS SDK : FederatedSignIn Failed to retrieve authorization token on Amplify.API.post

I've been working with the Amplify SDK to get federatedSignIn working with my iOS app with "Sign in with Apple" and Cognito to eventually make calls to API Gateway / Lambda functions.
TL;DR : My access token does not appear to be "automatically included in outbound requests" to my API as per the last paragraph of this section of the docs : Cognito User pool authorization
I have successfully authenticated using the tutorial found here Authentication Getting Started and other various Youtube videos on the Amazon Web Services channel.
Upon successful sign in through Apple I'm given an ASAuthorizationAppleIDCredential object. This contains the user field (token) which I pass to the Amplify.Auth class using the following Swift code :
func signIn (with userId: String)
{
guard
let plugin = try? Amplify.Auth.getPlugin(for: AWSCognitoAuthPlugin().key),
let authPlugin = plugin as? AWSCognitoAuthPlugin,
case .awsMobileClient (let client) = authPlugin.getEscapeHatch()
else
{
return
}
client.federatedSignIn(providerName: AuthProvider.signInWithApple.rawValue, token: userId) { (state, error) in
if let unwrappedError = error
{
print (unwrappedError)
}
else if let unwrappedState = state
{
print ("Successful federated sign in:", unwrappedState)
}
}
}
All appears to be successful and to double check I use the following bit of code to ensure I'm authorized :
func getCredentialsState (for userId:String)
{
let provider = ASAuthorizationAppleIDProvider()
provider.getCredentialState(forUserID: userId) { (credentialsState, error) in
if let unwrappedError = error
{
print (unwrappedError)
}
switch credentialsState
{
case .authorized:
print ("User Authorized")
case .notFound, .revoked:
print ("User Unauthenticated")
case .transferred:
print ("User Needs Transfer")
#unknown default:
print ("User Handle new use cases")
}
}
}
In the console I see "User Authorized" so everything appears to be working well.
However when I then go to make a call to Amplify.API.post I get the following error:
[Amplify] AWSMobileClient Event listener - signedOutFederatedTokensInvalid
Failed APIError: Failed to retrieve authorization token.
Caused by:
AuthError: Session expired could not fetch cognito tokens
Recovery suggestion: Invoke Auth.signIn to re-authenticate the user
My function for doing the POST is as follows :
func postTest ()
{
let message = #"{'message": "my Test"}"#
let request = RESTRequest (path: "/test", body: message.data(using: .utf8))
Amplify.API.post (request:request)
{
result in switch result
{
case .success(let data):
let str = String (decoding: data, as: UTF8.self)
print ("Success \(str)")
case .failure(let apiError):
print ("Failed", apiError)
}
}
}`
I then went into the API Gateway UI and changed the generated Method Request on my resource from AWS IAM to my Cognito User Pool Authorizer thinking this was the issue. I also changed the awsAPIPlugin authorizationType to "AMAZON_COGNITO_USER_POOLS" in my amplifyconfiguration.json file. This unfortunately did not have any affect.
I've seen posts such as this issue User is not created in Cognito User pool for users logging in with Google federated login #1937 where people discuss the problem of having to to use a web ui to bring up the social sign in. I understand that Apple will reject your app sometimes for this. Therefore this is not a solution.
I then found this post which seems to resolve the issue however this appears to use the old version of the SDK? Get JWT Token using federatedSignIn #1276
I'm not great with Swift (I'm still an Objective C expert, but am slowly learning Swift) so I'm uncertain which path to go here and whether this is actually a solution? It does seem to be quite more complicated than the function I have that does my POST? The RESTRequest does seem to be a simple and easy solution but I'm uncertain how to pass it the Authorization token (or even how to get the token if it is needed here).
However, everything I've read about the SDK is that the authorization should be handled automatically in the background according the docs in my first link above. Specifically pointed out, again, here : Cognito User pool authorization. The last paragraph here states 👍
With this configuration, your access token will automatically be included in outbound requests to your API, as an Authorization header.
Therefore, what am I missing here as this does not appear to automatically include my access token to my outbound requests to my API?

How to login again after redirect to /login without any http error

I have an application that authenticates on a website without any API, just to the login page and then save the cookies for next requests.
The problem is what happens when the session or the cookies has expired, the website redirects to /login with HTTP 200. (I don't have access to website.)
I'm using Alamofire library, it includes "Adapting and Retrying Requests" and its good for things like OAuth, but not for my case, because RequestRetrier only is called on some HTTP error codes, and i always receive OK 200.
I only can catch the redirect url and if it contains "/login" then i know the session has expired.
I tried using taskWillPerformHTTPRedirection something like this
delegate.taskWillPerformHTTPRedirection = { session, task, response, request in
var f_request = request
if (request.url!.absoluteString.contains("login.jsp")) {
loginAgain(){
// After successfully login return the original request.
f_request = task.originalRequest
}
return f_request
}
But of course the login request is asynchronous call, so the login is made after the original request.
How should I do it? Synchronous login call? i'm missing some in Alamofire?
Okay, I did not know the existence of: "taskWillPerformHTTPRedirectionWithCompletion"
so.. problem solved.
delegate.taskWillPerformHTTPRedirectionWithCompletion = { session, task, response, request, completion in
if(needLoginLogic){
login_bg(){ (result) in
switch result {
case .success:
// Make the original request inteast of "/login" request
completion(task.originalRequest)
break
case .failure(let error):
// Catch error later.
completion(request)
break
}
}
}else{
// Just make the request
completion(request)
}
}

network requests being saved in memory?

This has got to be one of the strangest thing I've come across...
Simple network request using alamofire
manager.request(PostRouter.readPosts(pn: pn)).validate().responseJSON {
response in
switch response.result {
case .success(let json):
if let json = json as? JSON,
let postsArray = json["posts"] as? [JSON],
let posts = Post.build(from: postsArray) {
completion(posts, nil)
}
else {
completion(nil, NetworkingError.jsonParsingError)
}
case .failure(let error):
completion(nil, error)
}
}
The same thing happens whether running from the simulator or mobile.
make request in airplane mode -> error of no internet connection.
make request again with internet -> loads posts
make request again in airplane mode -> loads posts without internet. Returns a success case with json value.
Even if in step 3 I make the request with an internet connection and have since modified the value of the data between steps 2 and 3, it will still return the exact same data from step 2 instead of fetching new data. It's almost like the whole request, including the data is saved in memory.
The only way I can actually make a new request to fetch the new data is by removing it from my phone and installing it again. The issue then repeats itself.
This happens to all the requests I make from the app. Also, The issue isn't linked to Alamofire because without it the issue still occurs
It's probably not an issue but a feature. Foundation will automatically cache responses. Check the response's cache headers (like Expires, Cache-Control, ETag etc.) if the server enables caching.

Why am I getting error code 403 while trying to fetch google+ profile image from my ios app?

I have a google iD of some user and I want to display his google profile photo in my app. In my swift code I try to fetch the json with necessary information (based on this answer https://stackoverflow.com/a/22526130/3766930 ). This is my code:
Alamofire.request(.GET, "https://www.googleapis.com/plus/v1/people/10263...4252?key=AI...Oo")
.responseJSON { response in
print(response)
switch response.result {
case .Success:
dispatch_async(dispatch_get_main_queue(),{
if let jsonData = response.result.value as? [[String: AnyObject]] {
print(jsonData)
}
})
case .Failure(let error):
print("SWITCH ERROR")
print(error)
}
}
but as a response I'm getting this error:
error = {
code = 403;
errors = (
{
domain = usageLimits;
extendedHelp = "https://console.developers.google.com";
message = "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.";
reason = ipRefererBlocked;
}
);
message = "There is a per-IP or per-Referer restriction configured on your API key and the request does not match these restrictions. Please use the Google Developers Console to update your API key configuration if request from this IP or referer should be allowed.";
};
I went carefully through my google developers console and I don't have any IP restrictions set up. This is how it looks so far:
I'm using the api key from here:
as you can see there is no domain limitation here:
What might be the reason of this weird error?
Remove the iOS bundle identifier restrictions for the API key in Google Developers Console. The bundle identifier restrictions only work when you use the Google client libraries.

Resources