iOS: Get Latest Tweet Text Only From Specific User - ios

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

Related

login user with GET request swift

I have created a screen with a text field called customer_number text field and another screen with a text field called password text field. I want to integrate my app with an existing API made by the backend developers. I am new to IOS Development and I don't know how to go about it. How do I make a get request and pass the login credentials for the user to login?
I want to get the customer number from the API and pass it to the app and enable the customer to log in.
I think this question is too big and complex to be replied exhaustively. You didn't tell us about the API. What kind of input does it take? What kind of response?
Supposing the simplest case. You API expects JSON objects as input and respond with another JSON object containing the information you request.
I usually do tasks like this using the NSURLRequest.
let js = ["Username":username, "Password":password]
let session = URLSession.init(configuration: .default)
let url = URL(...)
var req = URLRequest.init(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10)
req.httpMethod = "POST"
// Add some header key-value pairs
req.addValue(..., forHTTPHeaderField: ...)
...
let task = session.dataTask(with: request) { (data, response, error) in
guard error == nil else { return }
guard let responseData = data else { return }
let code = (response as! HTTPURLResponse).statusCode
// Checking for code == 200 states for authorised user. Generally log-in APIs should return some 4xx code if not allowed or non-authorised user.
if code == 200 {
// Now we try to convert returned data as a JSON object
do {
let json = try JSONSerialization.jsonObject(with: responseData, options: [])
// use your json object here, for example checking if contains the user number...
} catch {
// handle errors
}
}
}
task.resume()
I coded this very quickly, please check the correctness of al mechanism!

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

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)

Facebook graph API link parameter returning nil

I am trying to store a logged in facebook user's facebook username (eg www.facebook.com/james.dean01) in order to connect people via messenger (similar to How to open Facebook Messenger and direct to someone?). I am configuring a button which will send a user directly to someones messenger chat but to do so I need their username/facebook URL. I am attempting to use the "link" property (Facebook graph API: https://developers.facebook.com/docs/graph-api/reference/user) to obtain a link to the user's profile which could be used for this purpose, only the link property (printed) returns nil. I am not sure what I am doing wrong. The aim is that each time a user logs in the data is read and the database is updated. Below is the code.
Any help would be greatly appreciated!
import FacebookCore
class FacebookService {
static let instance = FacebookService()
let params = ["fields": "email, first_name, last_name, link, picture, name"]
func recordUserData() {
let graphRequest = GraphRequest(graphPath: "me", parameters: params)
graphRequest.start {
(urlResponse, requestResult) in
switch requestResult {
case .failed(let error):
print("error in graph request:", error)
break
case .success(let graphResponse):
if let responseDictionary = graphResponse.dictionaryValue {
print(responseDictionary)
let link = responseDictionary["link"] as? String
let email = responseDictionary["email"] as? String
let fbId = responseDictionary["id"] as? String
let name = responseDictionary["name"] as? String
let picture = responseDictionary["picture"] as? NSDictionary
let data = picture!["data"] as? NSDictionary
let url = data!["url"] as? String
print("Link: \(link)")
print(url)
}
}
}
}
}
You need to ask for the necessary permission, https://developers.facebook.com/docs/facebook-login/permissions#reference-user_link
And the use of this permission requires review by Facebook, before you can use it in your live app.
Not sure you would get this through review though, because what you would be doing is essentially what it says there is a not allowed use case:
Attempt to programmatically determine someone's Facebook username or canonical User ID.
So no guarantee Facebook will approve this; you can only try and submit it for review and see what feedback you get.

How to check if my contact list members are registered with my app just like whatsapp does?

I am creating a chat app, for which I need to check each of my contact list members if they are registered with my app and show the registered members list in my app.
Currently I am calling an API to check every number one by one. In case of 800 contacts it is getting called 800 times. I know this is not best way to do it. So, can some one please help me out and suggest me to do it in better way?
Below is my code:
func createContactNumbersArray() {
for i in 0...self.objects.count-1 {
let contact:CNContact! = self.objects[i]
if contact.phoneNumbers.count > 0 {
for j in 0...contact.phoneNumbers.count-1 {
print((contact.phoneNumbers[j].value).value(forKey: "digits")!)
let tappedContactMobileNumber = (contact.phoneNumbers[j].value).value(forKey: "digits")
let phoneNo = self.separateISDCodeMobileNo(mobileNo:tappedContactMobileNumber as! String)
contactNumbersArray.append(phoneNo.1)
}
}
}
callGetAppUserDetailService(mobileNumber: self.contactNumbersArray[currentIndex] as! String)
}
I am doing this whole process in the background and refreshing the member list on front in current scenario.
I want to make the whole process as fast as Whatsapp.
There is no way to do it without back-end modifications. So you need to work closely with your back-end engineer and build an API for this.
Here is an advise how you can build this API:
To have 2 APIs:
1) Upload the whole user address book to the back-end in a single request, something like:
let addressBook = NSMutableOrderedSet()
let contact1 = AddressBookContact()
contact1.name = "Jony Ive"
contact1.phone = "1-800-300-2000"
addressBook.add(contact1)
let contact2 = AddressBookContact()
contact2.name = "Steve Why"
contact2.phone = "412739123123"
addressBook.add(contact2)
let deviceUDID = nil
Request.uploadAddressBook(withUdid: deviceUDID, addressBook: addressBook, force: false, successBlock: { (updates) in
}) { (error) in
}
2) As a next step - retrieve a list of already registered users with phones from your address book, something like this:
let deviceUDID = nil
Request.registeredUsersFromAddressBook(withUdid: nil, successBlock: { (users) in
}) { (error) in
}
so now you can show it in UI
Found this example here https://developers.connectycube.com/ios/address-book
In fact,you can do little on client.
The normal way is: Server provide an interface that support check a phonenumber array, and return the phonenumbers has registered on server.
I think you need to save user's phone number to your database when user registers your app. Then you can find out contacts which have already used your chat app.

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

Resources