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¢er={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¢er=\(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()
}
Related
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]
}
}];
My iOS application allows a user to submit a complaint to an online REST API with the following parameters:
Data Fields: such as name, phone number, ...
Voice: recorded from microphone
Image/Video: selected from photo gallery
1- how can i do that with swift?
2- how to get back an ID field from the server after submission?
3- how to manage an upload progress for the voice and media files?
Regards
After few weeks working hardly on it, here is my experience using Swift 3.1 which is run smoothly:
//use POSTMAN plugin in Chrome browser to get the read header for your API (optional):
let headers = [
"cache-control": "no-cache",
"postman-token": "00000000-1111-2222-3333-444444444"]
//this is the important part:
let strQuery: String = "mobileNo=" + txtMobileNB.text! + "&fullname=" + txtName.text!
let request = try? NSMutableURLRequest(url: NSURL(string: "http://service.website.com/apiname/?" + strQuery)! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request?.httpMethod = "POST"
request?.allHTTPHeaderFields = headers
if request != nil {
let session = URLSession.shared
let dataTask = session.dataTask(with: request! as URLRequest) {data,response,error in
if let content = data
{
let responseData = String(data: content, encoding: String.Encoding.utf8)
//feedback from server:
print(responseData)
//call success function:
self.showDone()
} else {
//call error function:
self.showWrong()
}
}
dataTask.resume()
} else {
//call error function:
self.showWrong()
}
Regarding the other part "how to upload", i've found this framework is a good one (called rebekka) to start your upload project through iOS apps.
hope this helps someone :)
Let me start off by saying the purpose of this code is so I can practice on various other sites with login pages or forms. This is why I do no wish to use Facebook's SDK. So please...
Do not point me to Facebook's SDK (many other questions specifically asking for without SDK have been given SDK answers)
Ideally I would like to create an app that has preset information that will login to a site (such as Facebook) when the app opens or a button is pressed
I'd prefer an answer in Swift but I can read Objective - C and may be able to decipher it
Here is some sample code I've tried:
let myURL = NSURL(string: "https://mobile.facebook.com")
let request = NSMutableURLRequest(URL: myURL!)
request.HTTPMethod = "POST"
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-type")
let postString = "email=*email&pass=*pass&login=Log In"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let postInt = postString.characters.count
request.setValue("\(postInt)", forHTTPHeaderField: "Content-length")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil {
print("error=\(error)")
}
if let HTTPResponse = response as? NSHTTPURLResponse {
let sCode = HTTPResponse.statusCode
if sCode == 200 {
// Then do something.
self.webView.loadRequest(request)
}
}
print("respone = \(response)")
}
task.resume()
*email = The user's email
*pass = The user's password
note: email, pass, Log In were taken from the form name values on the html code.
Current results- I am able to get the email to appear on opening of the app but the password is blank and it doesn't appear to have attempted a log in.
Please help and let me know if you need any clarifications
PS I've been looking for about a week now to no avail so I apologize if the answer is somewhere. I am not completely familiar with terminology to look for it.
I have submitted an app to iTunes and Apple rejected it because of a crash.
I symbolicated and analyzed the crashreport and saw that it crash at a json call.
I try to reproduce it and I found that it just happens when I turn off my wlan.
Does Apple test apps offline?
How can I handle this error? And make my jsoncall better.
This is my method:
var session = NSURLSession.sharedSession();
var uri = "/GetNews";
let request : NSMutableURLRequest = CreateRequest(uri, HTTPmethod: "GET");
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil;
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: error) as? Dictionary<String, AnyObject>;
let resp : NewsResponse = NewsResponse(jsonData: jsonResult!);
completionHandler?(resp);
});
task.resume();
It crashs at let resp..., because jsonResult is nil and I use !
Of course Apple tests apps offline, and you should too. You should plan on every call that requires an internet connection failing, and you should handle every error appropriately.
The appropriately part is up to your app. For example, some apps (like Facebook) let you read posts you've already downloaded, and queue up posts you write to be sent when you get an internet connection. Some apps just don't work at all without an internet connection and it doesn't make sense for them to do anything but put up an error message (like, for example, a iTunes radio).
If your app is a news reader, perhaps the best thing to do is use a cache and let them read news they've downloaded in the past. A simple, unobtrusive message letting them know they're offline and new articles will be downloaded once they're back on would suffice; a crash, though, is very bad in terms of usability and utility.
TO FIX CRASH
As Eric stated, you should use "safe unwrapping", better known as optional binding. Try this:
var session = NSURLSession.sharedSession();
var uri = "/GetNews";
let request : NSMutableURLRequest = CreateRequest(uri, HTTPmethod: "GET");
let task : NSURLSessionDataTask = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil;
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: error) as? Dictionary<String, AnyObject>;
//if non-nil, assigns jsonResult to nonNilJsonResult
if let nonNilJsonResult = jsonResult {
let resp : NewsResponse = NewsResponse(jsonData: nonNilJsonResult!);
completionHandler?(resp);
}
});
task.resume();
Hi I'm downloading JSON in my app to the device with NSJSONSerialization and it seems that when I update the JSON file and re-run the download JSON function it doesn't download the new JSON. It's just downloading the non updated JSON file. I've tried running the app on different devices and it works the first time but once I update the JSON again it doesn't download the new JSON. I'm thinking it may be getting cached but I'm not sure.
Here's my code:
func downloadJSON(){
let p = NSURLRequest(URL: NSURL(string: "https://themartini.co/pythonStuff/quotey.json")!)
let sharedSession = NSURLSession.sharedSession()
let dwn = sharedSession.dataTaskWithRequest(p, completionHandler: { (data : NSData!,re : NSURLResponse!, error: NSError!) -> Void in
if error == nil {
let js : AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as NSArray // downloads JSON and puuts it into an array
println(js)
dispatch_async(dispatch_get_main_queue()){
self.quotes = js as NSArray
NSNotificationCenter.defaultCenter().postNotificationName("dataTaskFinished", object: nil)
}
}
})
dwn.resume()
}
Any ideas? Thanks.
You should pass the correct cache policy to your NSURLRequest. There is an alternative constructor that includes this parameter.
let p = NSURLRequest(URL: url,
cachePolicy: ReloadIgnoringLocalCacheData,
timeoutInterval: 15.0)
You can add a cachebuster to your NSURLRequest. (change the url to https://themartini.co/pythonStuff/quotey.json?23421231231
where the string of numbers at the end is random. This will break the cache. Also, instead of using NSURLSession, look into NSURLConnection.SendAsynchroniousRequest