Facebook Graph API Issues - ios

i am implementing facebook graph APi for get posts list but i am getting error in this Here Is my Code
var Requset : FBSDKGraphRequest
print("\(FBSDKAccessToken.current())")
let acessToken = String(format:"%#", FBSDKAccessToken.current().tokenString) as String
print("\(acessToken)")
let parameters1 = ["access_token":FBSDKAccessToken.current().tokenString]
Requset = FBSDKGraphRequest(graphPath:"me/?fields=feed{message,full_picture,id,application,likes{name,pic_crop},comments{message,from,created_time},created_time}", parameters:parameters1, httpMethod:"GET")
Requset.start(completionHandler: { (connection, result, error) -> Void in
//MBProgressHUD.hideHUDForView(appDelegate.window, animated: true)
if ((error) != nil)
{
print("Error: \(error)")
}
else
{
print("fetched user: \(result)")
//var dataDict: AnyObject = (result! as AnyObject).object(forKey: "data")!
}
i am getting error in this error is given below
Error: Optional(Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSUnderlyingError=0x60000005fbf0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}, NSErrorFailingURLStringKey=(null)?
can any one tell me how to solve this

Related

Firebase function not works on production, from IOS

I do a call to Firebase function from ios/swift.
let functions = Functions.functions()
func callWrapper(funcName: String, data: Any? = nil) async -> [String: Any]? {
do {
let result = try await functions.httpsCallable(funcName).call(data)
return result.data as? [String : Any]
} catch {
if let error = error as NSError? {
if error.domain == FunctionsErrorDomain {
let code = FunctionsErrorCode(rawValue: error.code)
let message = error.localizedDescription
let details = error.userInfo[FunctionsErrorDetailsKey]
}
//todo handle
print(error)
}
return nil
}
}
I got next error.
2023-01-05 22:29:48.821609+0200 wallpapers[41492:641302] Task
<50374BAD-C312-450E-9770-B8300BE8FDB9>.<1> finished with error [-1007]
Error Domain=NSURLErrorDomain Code=-1007 "too many HTTP redirects"
UserInfo={NSLocalizedDescription=too many HTTP redirects,
NSErrorFailingURLStringKey=https://accounts.google.com/v3/signin/rejected?continue=https://uc.appengine.google.com/_ah/conflogin?state%3D~AJKiYcH_jc-hcv6OubZGrM13BmNN37rWX4x6rmTm7rZ4-Lqnr9Kk2C00oVNYR97TOiJ8lcR7vP91c9rv6o89HuwIlj85hxjrj63gbmu1jzGKzkU6S_kvHXv7yGdtaOWJnImTm02c6w9igKt3PbbWcawMsOafXEizRAd8jrT0jSe704DhXZ51m8IgAKv0kXxnblLuu3-DFmm-Uvi30sCPXIRGr_XG2DrMenI-zYGRjTiXf2uBVzIom7nVmKoCxIS7dGTvQozrDisq&dsh=S-1861899242:1672950586288679&flowEntry=ServiceLogin&flowName=WebLiteSignIn&ifkv=AeAAQh7QjO_naDvlYC2CVX-wduN9ft7CbGKMTlrMDHmAba7cHNPiDVDd4AQJzvAJgPnBpbS7sCeK0w&rhlk=no&rrk=32,
NSErrorFailingURLKey=https://accounts.google.com/v3/signin/rejected?continue=https://uc.appengine.google.com/_ah/conflogin?state%3D~AJKiYcH_jc-hcv6OubZGrM13BmNN37rWX4x6rmTm7rZ4-Lqnr9Kk2C00oVNYR97TOiJ8lcR7vP91c9rv6o89HuwIlj85hxjrj63gbmu1jzGKzkU6S_kvHXv7yGdtaOWJnImTm02c6w9igKt3PbbWcawMsOafXEizRAd8jrT0jSe704DhXZ51m8IgAKv0kXxnblLuu3-DFmm-Uvi30sCPXIRGr_XG2DrMenI-zYGRjTiXf2uBVzIom7nVmKoCxIS7dGTvQozrDisq&dsh=S-1861899242:1672950586288679&flowEntry=ServiceLogin&flowName=WebLiteSignIn&ifkv=AeAAQh7QjO_naDvlYC2CVX-wduN9ft7CbGKMTlrMDHmAba7cHNPiDVDd4AQJzvAJgPnBpbS7sCeK0w&rhlk=no&rrk=32,
_NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <50374BAD-C312-450E-9770-B8300BE8FDB9>.<1>" ), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <50374BAD-C312-450E-9770-B8300BE8FDB9>.<1>,
NSUnderlyingError=0x6000005f7c00 {Error Domain=kCFErrorDomainCFNetwork
Code=-1007 "(null)"}}.
If i run on local firebase simulator, it works fine
functions.useEmulator(withHost: "localhost", port: 5001)
i assume, i call function anonymously, and this might be a problem hovewer i want to do it as anonymous unauthorized user. Is it possible somehow to allow function to be called from unauthorized user? Or how to fix this problem? Thanks

Timeout error when post public key string with URLSession

I am creating a rsa key pair and send the public key to my api. But the post request fails with Timeout error. Following is my function for the request:
func perform<T: Decodable>(reqData: Data, with completion: #escaping (T?) -> Void) {
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
// insert json data to the request
request.httpBody = reqData
print("jsonData: ", String(data: request.httpBody!, encoding: .utf8) ?? "no body data")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let error = error else {
print(error)
completion(nil)
return
}
guard let data = data else {
completion(nil)
return
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
completion(try? decoder.decode(T.self, from: data))
}
task.resume()
}
JSON Object sent in POST:
{
"publicKey" : "MIIBCgKCAQEA4lS13W+TXZhUXy5yB2NpeulCVb1ZSaReopeKrahjKmUx4NQxVXruEYCY3LpjZcSy8xiudVG3GBIMnPLtaMbc5WAYDj1M2OwnpNHdQ8SKtZ1tdA6iRjfOXGUa1n8FMIMKU5ynTSAiSoh+8gGrY0L6jTsCSdLO5ZU53LQFHSESM8JuBeNZozolb\/cKb38ylercVeVpo8egoA8UqHezK23VUJ23faxMmMZDJxVn5pfFedxBTLxwU65KQY8Z4izaFjuPLoGe5JZkXyYNMcrYloDCBG5m9BFiXVkoLEDmGFGfWLMJcqL+D2CszqJ4h712ZR6LYRNtIbo\/HG9KR7XCtap3QwIDAQAB"
}
I have tested the url in Postman and it works good there. But it is giving my follwoing error when I call it from my app:
Task <6AB1B692-9CBF-4E37-80C6-4F37FD43264B>.<1> finished with error [-1001] Error Domain=NSURLErrorDomain Code=-1001 "The request timed out." UserInfo={_kCFStreamErrorCodeKey=-2102, NSUnderlyingError=0x280299c50 {Error Domain=kCFErrorDomainCFNetwork Code=-1001 "(null)" UserInfo={_kCFStreamErrorCodeKey=-2102, _kCFStreamErrorDomainKey=4}}, _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <6AB1B692-9CBF-4E37-80C6-4F37FD43264B>.<1>, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <6AB1B692-9CBF-4E37-80C6-4F37FD43264B>.<1>"
), NSLocalizedDescription=The request timed out., NSErrorFailingURLStringKey=http://192.168.178.205:3000/savepublickey, NSErrorFailingURLKey=http://192.168.178.205:3000/savepublickey, _kCFStreamErrorDomainKey=4}
Following is my server side code in Node.js:
app.post('/savepublickey', (req, res) => {
console.log("savepublickey");
console.log(req.body);
let data = JSON.parse(JSON.stringify(req.body, null, 2));
if (data['publicKey'] != null && data['publicKey'] != "") {
console.log("Success");
publicKey = data['publicKey'];
res.status(200).json({
"Status": "Success"
}).send();
} else {
console.log("Fail");
res.status(500).json({
"Status": "Invalid request"
}).send();
}
})

swift 3 facebook sdk get friends list

I need to get all my friends list:
I found this code:
var fbRequestFriends: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "/{friend-list-id}", parameters: [AnyHashable : Any]())
fbRequestFriends.start { (connection, result, error) in
if error == nil && result != nil {
print("Request Friends result : \(result!)")
} else {
print("Error \(error)")
}
}
But in return I get this error:
Error Optional(Error Domain=NSURLErrorDomain Code=-1002 "unsupported
URL"
UserInfo={NSErrorFailingURLStringKey=(null)?access_token=EAAZAaT5Yj9qQBABsXA5KGpwvGX6wIdgX6h9mLtzz6YtgjiOB12XwWxl1MrDJLtZChWSOOKXDiizZCu7uZAixBmqP97HYUXkeg3lkTeeeyjmvhZBOZBibrp2Exa9uZB7V5fflJTvISF2aqK94H7E52svqei6SHvxi3W9vcynSI8hPQBBSawND9NHQif0wYIPuHIpbzl6ErBErvk6nm4ysMo1ZA0BFHVmflVYZD&format=json&include_headers=false&sdk=ios,
NSErrorFailingURLKey=(null)?access_token=EAAZAaT5Yj9qQBABsXA5KGpwvGX6wIdgX6h9mLtzz6YtgjiOB12XwWxl1MrDJLtZChWSOOKXDiizZCu7uZAixBmqP97HYUXkeg3lkTeeeyjmvhZBOZBibrp2Exa9uZB7V5fflJTvISF2aqK94H7E52svqei6SHvxi3W9vcynSI8hPQBBSawND9NHQif0wYIPuHIpbzl6ErBErvk6nm4ysMo1ZA0BFHVmflVYZD&format=json&include_headers=false&sdk=ios,
NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x7a6285b0
{Error Domain=kCFErrorDomainCFNetwork Code=-1002 "unsupported URL"
UserInfo={NSErrorFailingURLKey=(null)?access_token=EAAZAaT5Yj9qQBABsXA5KGpwvGX6wIdgX6h9mLtzz6YtgjiOB12XwWxl1MrDJLtZChWSOOKXDiizZCu7uZAixBmqP97HYUXkeg3lkTeeeyjmvhZBOZBibrp2Exa9uZB7V5fflJTvISF2aqK94H7E52svqei6SHvxi3W9vcynSI8hPQBBSawND9NHQif0wYIPuHIpbzl6ErBErvk6nm4ysMo1ZA0BFHVmflVYZD&format=json&include_headers=false&sdk=ios,
NSErrorFailingURLStringKey=(null)?access_token=EAAZAaT5Yj9qQBABsXA5KGpwvGX6wIdgX6h9mLtzz6YtgjiOB12XwWxl1MrDJLtZChWSOOKXDiizZCu7uZAixBmqP97HYUXkeg3lkTeeeyjmvhZBOZBibrp2Exa9uZB7V5fflJTvISF2aqK94H7E52
#CBroe is right, this is how the code should look like
let params = ["fields": "id, first_name, last_name, name, email, picture"]
let graphRequest = FBSDKGraphRequest(graphPath: "/me/friends", parameters: params)
let connection = FBSDKGraphRequestConnection()
connection.add(graphRequest, completionHandler: { (connection, result, error) in
if error == nil {
if let userData = result as? [String:Any] {
print(userData)
}
} else {
print("Error Getting Friends \(error)");
}
})
connection.start()

Unsupported URL swift ios sending Http request

I'm trying to send an http request in swift.
I got a method (sendHttpRequest) that take as argument a dictionary<String,AnyObject> and trying to send a request to localhost with a little server in php. When I tap button that call this function an error occur
"Optional(Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSErrorFailingURLStringKey=46.101.145.122/salvobertoncini.com/servo.php, NSErrorFailingURLKey=46.101.145.122/salvobertoncini.com/servo.php, NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x1763cef0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}})"
Here is the code:
func sendHttpRequests(data : Dictionary<String, AnyObject>)
{
let session = NSURLSession.sharedSession()
do
{
let request = try NSJSONSerialization.dataWithJSONObject(data, options: .PrettyPrinted)
let url = NSURL ( string : "127.0.0.1/Server/servo.php")
let finalRequest = NSMutableURLRequest(URL: url!)
finalRequest.HTTPMethod = "POST"
finalRequest.HTTPBody = request
let task = session.dataTaskWithRequest(finalRequest){ data,response,error in
if error != nil
{
print("Error -> \(error)")
}
do
{
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
print("Result -> \(result)")
}
catch
{
print("Error -> \(error)")
}
}
task.resume()
}
catch
{
print(error)
}
}

Facebook GET request - Should contain “fields” parameter for /me/friends

func getFbFriendsAndSendToServer() {
let request = FBSDKGraphRequest(graphPath:"/me/friends", parameters: ["fields": "id, name, email"]);
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
//Save friends ID
let fbFriendsData : NSArray = result["data"] as! NSArray
for fbData in fbFriendsData {
self.friendsFbIDs.addObject(fbData["id"] as! String);
}
//send friends FB IDs to remote server
self.sendFriendsIDsOnServer()
}
else {
self.showAlertViewWithRetryButton("PullCar", message: "Unable to get your Facebook friends. Please check your internet connection and try again.", tag: 102)
}
}
}
This Piece of code will not give me error as below.
-[ Facebook Graph API GET request - Should contain “fields” parameter ]

Resources