Load twitter posts from different users - ios

Hi need to load twitter posts from different users.
I know how to load post from single user.
Perform request with search query FROM:<username>.
Do you know the way how to load posts from different users?
I tried something like this FROM:<username1>&&<username2> - but it doesn't work.
Any ideas?

You can make use of TwitterKit framework which is available in cocoapods GitHub - https://github.com/twitter/twitter-kit-ios/wiki/Access-Twitter's-REST-API
Cocoapods - https://cocoapods.org/pods/TwitterKit
Its twitter's own library, so you can always rely on that.
To load multiple tweets you need to use the below code
let client = TWTRAPIClient()
let tweetIDs = ["510908888888487103", "510908133777777104"]
client.loadTweets(withIDs: tweetIDs) { (tweets, error) -> Void in
// handle the response or error
}
If you want to to access other Twitter API endpoints, you can construct a request manually also like below
let client = TWTRAPIClient()
let statusesShowEndpoint = "https://api.twitter.com/1.1/statuses/show.json"
let params = ["id": "20"]
var clientError : NSError?
let request = client.urlRequest(withMethod: "GET", url: statusesShowEndpoint, parameters: params, error: &clientError)
client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
if connectionError != nil {
print("Error: \(connectionError)")
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: [])
print("json: \(json)")
} catch let jsonError as NSError {
print("json error: \(jsonError.localizedDescription)")
}
}
Hope this one helps.

I found an approach. I have to use Twitter iOS SDK and TWTRAPIClient for performing the request. https://api.twitter.com/1.1/statuses/user_timeline.json is endpoint for getting tweets of certain user with some username.
NSURLRequest *r = [[TWTRAPIClient new] URLRequestWithMethod:#"GET"
URL:#"https://api.twitter.com/1.1/statuses/user_timeline.json"
parameters:#{#"screen_name":name}
error:nil];
[[TWTRAPIClient new] sendTwitterRequest:r completion:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if(data){
NSArray *tweets = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
[TWTRTweet tweetsWithJSONArray:tweets]
}
}];

Related

None of the success and failure blocks are getting executing

This is my code
let url = URL(string: "http://demo6680989.mockable.io/getData")
let manager = AFHTTPSessionManager()
manager.get((url?.absoluteString)!, parameters: nil, progress: nil, success: {
(dataTask, responseObj) in
if let dict : NSDictionary = responseObj as? NSDictionary {
//print("Response: \(dict)")
AuditListParser().parseAudit(jsonData: dict)
}
}, failure: {
(dataTask, error) in
print(error.localizedDescription)
})
When I used this url in browser it is giving me some data but when i execute the above code it is neither going into success block nor fialure block.
1st time it was running properly and printed the data. I dont what happened suddenly, when i run it again this problem came
please help me
Normally, AFHTTPSessionManager's GET:(NSString *)URLString parameters:(NSDictionary *)parameters success:(void ( ^ ) ( NSURLSessionDataTask *task , id responseObject ))success failure:(void ( ^ ) ( NSURLSessionDataTask *task , NSError *error ))failure method returns NSURLSessionDataTask object. So, you should start that task somehow for it to return in success or failure block. Just get the object that is being returned from get() method, and call resume() method of that object. Good luck!
EDIT
Like this:
let task = manager.get((url?.absoluteString)!, parameters: nil, progress: nil, success: {
(dataTask, responseObj) in
if let dict : NSDictionary = responseObj as? NSDictionary {
//print("Response: \(dict)")
AuditListParser().parseAudit(jsonData: dict)
}
}, failure: {
(dataTask, error) in
print(error.localizedDescription)
})
task.resume()

Request failed: forbidden (403) for fabric twitterkit

I'm trying to extract the members of a list using the TwitterKit API for iOS. As I understand, doing this will allow me to be "guest-authenticated" bypassing the need for my personal consumer and consumer-secret keys.
The code below attempts to get the members of a list using this REST endpoint
let client = TWTRAPIClient()
let endpoint = "https://api.twitter.com/1.1/lists/members.json"
let params = ["owner_screen_name" : "palafo", "slug" : "breakingnews"]
var clientError : NSError?
let request = client.URLRequestWithMethod("GET", URL: endpoint, parameters: params, error: &clientError)
client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
if connectionError != nil {
print("Error: \(connectionError)")
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
print("json: \(json)")
} catch let jsonError as NSError {
print("json error: \(jsonError.localizedDescription)")
}
}
Running that gives me this error:
Error Domain=TwitterAPIErrorDomain Code=220 "Request failed: forbidden (403)" UserInfo={NSLocalizedFailureReason=Twitter API error : Your credentials do not allow access to this resource (code 220), TWTRNetworkingStatusCode=403, NSErrorFailingURLKey=https://api.twitter.com/1.1/lists/members.json?owner_screen_name=palafo&slug=breakingnews, NSLocalizedDescription=Request failed: forbidden (403)})
If I change endpoint to instead get the statuses in that list using this other REST endpoint, I get a proper JSON response.
let endpoint = "https://api.twitter.com/1.1/lists/statuses.json"
Does this mean that Fabric's guest authentication does not allow me to get the members of a list?
I solved mine by using clientWithUserId instead of just initializing using just init.
NSString *userID = [Twitter sharedInstance].sessionStore.session.userID;
TWTRAPIClient *client = [[TWTRAPIClient alloc] initWithUserID:userID];

Custom Made Web Service returning NIL in iOS Swift 2.0

I am trying to learn how to make a web service on my apache server, and then service the resulting JSON to an iOS application.
My web service certainly returns JSON information when I input the url, which is MYIP/?code=1 (the code could be anything, this is only for testing). Here is my PHP web service:
<?php
/**
* Created by PhpStorm.
* User: Clayton
* Date: 2/12/2016
* Time: 6:18 PM
*/
//process client request
header("Content-Type:application/json");
if(!empty($_GET['code'])){
$code = $_GET['code'];
$xml = simplexml_load_file("C:\Users\Clayton\Desktop\DataFiles\warehouse.city") or die("Error: Cannot create object");
$sum1 = $xml->to;
deliver_request(200,"Sum delivered", $sum1);
}
else{
// throw invalid request
deliver_request(404,"Sum not delivered", NULL);
}
function deliver_request($status, $status_message, $data){
header("HTTP/1.1 $status, $status_message");
$response['status'] = $status;
$response['status_message'] = $status_message;
$response['data'] = $data;
$json_response=json_encode($response);
echo $json_response;
}
?>
Now the issue that I am having, is when I go onto the iOS end, the data response is returning NIL, and I'm not sure why. Here is the swift code
let url = NSURL(string: "35.11.183.52/?code=1")
let session = NSURLSession.sharedSession()
session.dataTaskWithURL(url!, completionHandler:
{(data: NSData?, response:NSURLResponse?, error: NSError?) -> Void in
// Read the Json
do {
if let textString = NSString(data:data!, encoding: NSUTF8StringEncoding){
//Parse the Json to get the text
let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(
data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
let origin = jsonDictionary["status"] as! String
//update the label text
self.performSelectorOnMainThread("updateIPLabel:",
withObject: origin, waitUntilDone: false)
}
} catch {
print("something went wrong")
}
}).resume()
Any advice on why I'm getting NIL returned would be greatly appreciated. Again, I can see a response when I manually enter the URL into a browser on iOS, but can pull anything from the app code for some reason.

Receive response as NSDictionary instead of NSData

I'm trying to get the response from the server as NSDictionary instead of NSData, so first I'm using AFNetworking library and the server request these settings to be HTTP not JSON serializer as the following :
self.responseSerializer = AFHTTPResponseSerializer() as AFHTTPResponseSerializer
self.requestSerializer = AFHTTPRequestSerializer() as AFHTTPRequestSerializer
self.requestSerializer.HTTPMethodsEncodingParametersInURI = NSSet(array: ["GET"]) as! Set<String>
self.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json","text/json","text/javascript","text/html") as? Set<String>
Next is when i get the response from the server it comes to be NSData and its because I'm using AFHTTPRequestSerializer() and here is my code :
self.POST(addUserURL, parameters: dictionary, progress: nil, success: { (task, responseObject) -> Void in
print(responseObject)
}) { (task, error) -> Void in
}
Also inside AFNetworking block its not allowed to handle try and catch for NSJSONSerializtion which can be a possible solution but it doesn't work.
Use NSJSONSerialization for that as shown in below code :
do {
let jsonObject = try NSJSONSerialization.JSONObjectWithData(responseObject, options: .AllowFragments) as! NSDictionary
// use jsonObject here
} catch {
print("json error: \(error)")
}
As response that you get from the server doesn't have top level object that is either Array or Dictionary you have to specify custom reading options in that should be used by AFNetworking.
In order to do that you have to set responseSerializer property on an instance of AFURLSessionManager class. You can do it as follows:
let sessionManager = OLFURLSessionManager.init() //you probably want to keep session manager as a singleton
sessionManager.responseSerializer = AFJSONResponseSerializer.serializerWithReadingOptions(.AllowFragments)
//you should use that instance of session manager to create you data tasks
After that you should be able to correctly parse response from the server as follows:

Using Facebook's Graph API in iOS

I went over the Facebook developer docs and generally around the internet but couldn't quite understand how to use the Facebook Graph API in iOS.
Specifically, I need to fetch a list of nearby locations using a given latitude&longitude. I came across this:
GET /search?q={query}&type=place&center={lat},{lng}&distance={distance}
But I don't understand where to even begin.
I have the Facebook SDK set up.
How do I call such request?
Thanks in advance
I think that you need to use the Facebook Graph request methods, some thing like this
NSDictionary *params = #{#"fields" : #"", #"redirect" : #NO, #"type" : #"large"};
NSString *getPath = [NSString stringWithFormat:#"/%#/picture", #"fabebook_user_id"];
FBSDKGraphRequest *photoRequest = [[FBSDKGraphRequest alloc] initWithGraphPath:getPath parameters:params HTTPMethod:#"GET"];
with this method i am getting the user photo, I think so this method can be useful for you too :)
I managed by performing a simple URL request:
if let accessToken: FBSDKAccessToken? = FBSDKAccessToken.currentAccessToken() {
let urlString = "https://graph.facebook.com/search?type=place&center=\(geoPoint!.latitude),\(geoPoint!.longitude)&distance=1000&limit=10&access_token=\(accessToken!.tokenString)"
let URL = NSURL(string: urlString)!
let request = NSMutableURLRequest(URL: URL)
request.HTTPMethod = "GET"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
if response != nil {
let json = try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers)
print(json)
}
})
task.resume()
}

Resources