How to get facebook feed with images and videos along with text? - ios

I want to fetch logged user feeds within ios app, I have try with graph api that, graph api returns the data, its fine.
But when I have cross check the data to the actual facebook feed on facebook user page there are some problems found:
If post has text only than text coming on message key, along with post id,
If post has text with image/video only text coming on message key
And if post has only image/video than message key not coming.
I know message key is only for description/text but images? Is there any way to get the feed with whole content just same as appeared on facebook.
I have try below code:
For Login
FBSDKLoginManager().logOut()
FBSDKLoginManager().logIn(withReadPermissions: ["email", "public_profile", "user_posts"], from: self) { (result, error) in
if error != nil {
print("failed to start graph request: \(String(describing: error))")
return
}
// self.getPosts()//old
self.getFBPost()
}
For getFBPost
func getFBPost() {
FBSDKGraphRequest(graphPath: "/me/feed", parameters: nil)?.start(completionHandler: { (fbConnectionErr, result, error) in
// print(fbConnectionErr)
print(result)
//print(error)
})
}
Coming response like this:
{
"data": [
{
"message": "https://medium.com/frame-io-engineering/huge-images-small-phone-15414b30d39e",
"created_time": "2018-12-03T13:59:01+0000",
"id": "68288174406_653966194"
},
{
"created_time": "2018-12-01T13:43:02+0000",
"id": "68288174406_6528518443724"
},
{
"message": "I love my Mom",
"created_time": "2018-11-30T13:27:38+0000",
"id": "68288174406_652289420323"
}
}
as you can see the second post has only id and created time, while we check this on facebook page this the post with image, and third post has video but only text coming from graph api
Please guide whats wrong I did? Or What should I do to getting whole feed data in json formate just same as appeared on facebook?

You are not asking for any fields in the API call, so you only get default ones. It is called "Declarative Fields" (/me?fields=message,created_time,...) and came with v2.4:
https://developers.facebook.com/docs/graph-api/changelog/archive#v2_4_new_features
https://developers.facebook.com/docs/graph-api/using-graph-api/#reading

I have read the give doc that are shared by #luschn. And got the solution I forgot the declarative fields as #luschn suggest me, Now solution given below: Only need to change in the graph api,
FBSDKGraphRequest(graphPath: "/me/feed", parameters: ["fields":"created_time,attachments,type,message"])?.start(completionHandler: { (fbConnectionErr, result, error) in
print(fbConnectionErr)
print(result)
print(error)
let re = result as? [String: Any]
let data = re?["data"] as! [[String: Any]]
for dict in data {
print(dict)
}
})
OR
If you have page id you can use below url to hit the get api.
https://graph.facebook.com/(api_version)/(page_id)?fields=feed{created_time,attachments,message}&access_token=(token_id)

Related

iOS Swift / Wordpress API - POST to custom fields user registration?

When users register on my app, a user is created inside my Wordpress installation as well. I'm using Alamofire and the Wordpress API to accomplish this. That said, my user is created successfully, but for some reason any custom fields I have on the registration form aren't filled by my below code. The only fields that are filled properly are username, email and password.
How can I make it so that I'm able to POST data to custom fields on the registration form? Oddly, first_name & last_name are Wordpress fields (not custom) and data isn't saved to those either despite me POSTing to them.
My code below:
ViewController
// CREATE THE USER ACCOUNT IN WORDPRESS
#IBAction func registerNow(_ sender: Any) {
let params: Parameters = [
"username": emailAddress.text!,
"password": passwordField.text!,
"email": emailAddress.text!,
"nickname": firstName.text!,
"last_name": lastName.text!,
"first_name": firstName.text!,
"phone_number": phoneNumber.text!
]
AF.request("http://myurl.com/wp-json/wp/v2/users/register", method: .post, parameters: params, encoding: JSONEncoding.default, headers: nil).validate(statusCode: 200 ..< 299).responseJSON { AFdata in
do {
guard let jsonObject = try JSONSerialization.jsonObject(with: AFdata.data!) as? [String: Any] else {
print("Error: Cannot convert data to JSON object")
return
}
guard let prettyJsonData = try? JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted) else {
print("Error: Cannot convert JSON object to Pretty JSON data")
return
}
guard let prettyPrintedJson = String(data: prettyJsonData, encoding: .utf8) else {
print("Error: Could print JSON in String")
return
}
print(prettyPrintedJson)
} catch {
print("Error: Trying to convert JSON data to string")
return
}
}
}
The WordPress Core REST API does not include a user registration endpoint.
Endpoint list for Users: https://developer.wordpress.org/rest-api/reference/users/
There is a Create a User (POST /wp/v2/users) endpoint, but only logged-in admin users can add users on that endpoint if they have the create_users capability.
So the endpoint you specified is your own code. Thus, the error must be looked for primarily in that PHP code.
Your related question and the answer: WordPress Rest API - Register user - fields not saving?

POST API call using APIGateway returns "Internal Server Error" in swift 4, but works everywhere else

I created a nodejs lambda function in AWS and exposed it using APIGateway with methods GET, PUT, POST, and DELETE (all setup with proxy). All methods have been tested and work in AWS using APIGateway, and then outside of AWS using Postman.
First, I called the GET method for the endpoint in my Swift 4 project, and it is successful.
BUT I have tried just about everything to call the POST method in swift and cannot get it to execute successfully. This is what I am currently trying after researching online:
let awsEndpoint: String = "https://host/path"
guard let awsURL = URL(string: awsEndpoint) else {
print("Error: cannot create URL")
return
}
var postUrlRequest = URLRequest(url: awsURL)
postUrlRequest.httpMethod = "POST"
postUrlRequest.addValue("John Doe", forHTTPHeaderField: "name")
postUrlRequest.addValue("imageurl.com", forHTTPHeaderField: "imageUrl")
URLSession.shared.dataTask(with: postUrlRequest) { data, response, error in
guard let data = data else { return }
do {
guard let receivedTodo = try JSONSerialization.jsonObject(with: data,
options: []) as? [String: Any] else {
print("Error")
return
}
} catch let err{
print(err)
}
}.resume()
The response I get is ["message":"Internal Server Error"]. When I look at the logs in CloudWatch they are not very descriptive. The error log for the post call is:
"Execution failed due to configuration error: Malformed Lambda proxy response"
After researching this issue aws suggests to format the response in a specific way and I have updated my nodejs lambda function to mimmic this.
case "POST":
pool.getConnection(function(err, connection) {
const groupName = event.headers.name;
const imageUrl = event.headers.imageUrl;
var group = {Name: groupName, ImageUrl: imageUrl, IsActive:true, Created:date, Updated:date};
var query = "INSERT INTO Groups SET ?";
connection.query(query,group, function (error, results, fields) {
var responseBody = {
"key3": "value3",
"key2": "value2",
"key1": "value1"
};
var response = {
"statusCode": 200,
"headers": {
"my_header": "my_value"
},
"body": JSON.stringify(responseBody),
"isBase64Encoded": true
};
if (error) callback(error);
else callback(null, response)
connection.release();
});
});
break;
Like I said previously, this works when testing everywhere except swift 4. My GET call works with swift 4, so I do not think it is an issue with allowing anything in the info.plist but I could be wrong. I have tried just about everything, but cannot seem to get past this error.
I fixed this issue myself. After allowing ALL log output in API Gateway for that endpoint, I found that somewhere along the way my headers were being converted to all lowercase.
'imageUrl' became 'imageurl'
It was throwing an error because in my lambda function, it could not find 'imageUrl'
I think this is a conversion that is happening in APIGateway because I have never come across this issue with swift.

How to get user time line in JSON format using Twitter Kit in iOS SDK

I am trying to implement Twitter kit in my App. I have added SDK in my app & able to login. Now I have to get user time line data in JSON format (because I have to perform some manipulation & sorting over data). I found this link on Twitter to get time line for a user but in my case I need data in JSONformat not as DataSource object.
Can anyone suggest how to retrieve the time line data in JSON format using Twitter Kit?
TWTRAPIClient has several methods for making request and getting data. Use given code snippet to get user timelines.For parameters, kindly refer this page
let parameters = ["screen_name": "stevenhepting", "count": "3"]
var error : NSError?
let req = TWTRAPIClient().urlRequest(withMethod: "GET", url: "https://api.twitter.com/1.1/statuses/user_timeline.json", parameters: parameters, error: &error)
TWTRAPIClient().sendTwitterRequest(req, completion: { (response, data, error) in
do {
let response = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [[String : Any]]
if response != nil {
print((response! as NSArray).debugDescription)
}
}
catch {
print(error.localizedDescription)
}
})
To get other timelines, please refer
Twitter Developer Documentation

Get insights/page_fans for a Facebook page from Facebook's open graph

I'm trying to get the number of fans that a music artist has on their Facebook page, but it's not working. I've combed through the FBAPI docs as well as SO and still nothing. Here's my code:
func getHolychildInfo() {
//Make request
let newGraphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "/holychildmusic/insights/page_fans", parameters: ["period" : "lifetime", "show_description_from_api_doc" : "true", "fields": "read_insights"], httpMethod: "GET")
newGraphRequest.start(completionHandler: { (connection, result, error) in
if ((error) != nil) {
print("Holychild error getting insights: \(error.debugDescription)")
} else {
print("\nHolychild insights result:\n\n\(result)")
}
})
}
Here's my result:
data = (
);
paging = {
next = "https://graph.facebook.com/v2.8/holychildmusic/insights/page_fans?access_token=EAAIB5k3aWEEBAHBD9lZC5AAzZAVV8K8CGBfqaxcrLdZA7oZB2Gdar8cQphXj4VciloZAnZBKp5ZA59BmGloSNz847nFqZCTVsYZCl9rrOk88OnfCnDwwADKnkOO5EUhGumEbW96riHplgfBLdnZAEYmB2Qz4ZAH1sWbuftmGKDqPft4l5QAHSZAimIyI6sOHaKWiurRK201Af6NQCXGliZBsZAUYosUHttkUbo4CQZD&fields=read_insights&format=json&include_headers=false&period=lifetime&sdk=ios&show_description_from_api_doc=true&since=1487457711&until=1487716911";
previous = "https://graph.facebook.com/v2.8/holychildmusic/insights/page_fans?access_token=EAAIB5k3aWEEBAHBD9lZC5AAzZAVV8K8CGBfqaxcrLdZA7oZB2Gdar8cQphXj4VciloZAnZBKp5ZA59BmGloSNz847nFqZCTVsYZCl9rrOk88OnfCnDwwADKnkOO5EUhGumEbW96riHplgfBLdnZAEYmB2Qz4ZAH1sWbuftmGKDqPft4l5QAHSZAimIyI6sOHaKWiurRK201Af6NQCXGliZBsZAUYosUHttkUbo4CQZD&fields=read_insights&format=json&include_headers=false&period=lifetime&sdk=ios&show_description_from_api_doc=true&since=1486939311&until=1487198511";
};
As you can see, there is nothing in the "data" part of the response. The "page_fans" insights metric is supposed to return a number - among other things - but instead returns nothing.
All insights metrics besides the two public ones (page_fans_country and page_storytellers_by_country) require admin access to the page (admin user or page access token with read_insights permission.)
But the fan_count field of the page object is public, so just request that:
https://developers.facebook.com/tools/explorer/?method=GET&path=holychildmusic%3Ffields%3Dfan_count&version=v2.8

iOS: Get Latest Tweet Text Only From Specific User

I am wanting to get the latest tweet from a specific user that will not change. So if the specific user was Joe Smith, I would always get the latest tweet from him. I've looked into Fabric which seems to only get specific tweets by ID. The Twitter API looks fairly involved when all I am wanting is the latest tweet from a user. What is the best way to do this?
you could achive this by searching for a user and only using th first element
Using from:#tweethandle for example: from:StackOverflow and using only the first item!
You can search using TWTRAPIClient's URLRequestWithMethod
Ex: (using SwiftyJSON for parsing JSON) this should print the first tweet
let twError:NSErrorPointer = nil
let userID = Twitter.sharedInstance().sessionStore.session()?.userID
let client = TWTRAPIClient(userID: userID)
let request = client.URLRequestWithMethod("GET", URL: "https://api.twitter.com/1.1/search/tweets.json", parameters: ["q":"from:StackOverflow","result_type":"recent"], error: twError)
if twError == nil {
client.sendTwitterRequest(request, completion: { (response, data, error) -> Void in
let json = JSON(data: data!)
print(json["statuses"][0])
})
}
More info in the docs

Resources