How to post location with image to facebook in IOS? - ios

I am trying to share location along with image to facebook. I have successfully shared image but unable to share location. Below is my code of sharing image.
UIImage *facebookImage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#",imagesURL,str]]]];
NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
[params setObject:#"New Happening created on the HappenShare mobile app." forKey:#"message"];
[params setObject:facebookImage forKey:#"picture"];
[FBRequestConnection startWithGraphPath:#"me/photos" parameters:params HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection,id result,NSError *error)
{
if (error)
{
NSLog(#"error : %#",error);
}
else
{
NSLog(#"Result : %#",result);
}
}];
Now for sharing location what parameter should I add in above code. I am attaching an image also to understand better that how the shared location will look like.Below image shows that how the image with text will indicate a location into map. Please suggest me a solution for that.

Along with "message" and you also need "place" ID to post as param.
Request for a "publish_actions" so that you can post a place/location.
Below is the code i've used:
NSMutableDictionary *params = [NSMutableDictionary dictionary];
[params setObject:#"Hello World" forKey:#"message"];
[params setObject:#"110503255682430"/*sample place id*/ forKey:#"place"];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"/me/feed" parameters:params HTTPMethod:#"POST"] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
NSLog(#"result %#",result);
NSLog(#"error %#",error);
}];
You can also check this with the "administrator/tester" accounts given in Developer page -> your app -> Roles.
Use Graph explorer for better practice:
https://developers.facebook.com/tools/explorer/108895529478793?method=POST&path=me%2Ffeed%3F&version=v2.5&message=Hello%20world&place=110503255682430
Below code may help you in getting place id near your location:
NSMutableDictionary *params2 = [NSMutableDictionary dictionaryWithCapacity:4L];
[params2 setObject:[NSString stringWithFormat:#"%#,%#",YourLocation latitude,YourLocation longitude] forKey:#"center"]; //Hard code coordinates for test
[params2 setObject:#"place" forKey:#"type"];
[params2 setObject:#"100"/*meters*/ forKey:#"distance"];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"/search" parameters:params2 HTTPMethod:#"GET"] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
NSLog(#"RESPONSE!!! /search");
}];
OR
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"/search?type=place&center=YourLocationLat,YourLocationLong&distance=500" parameters:nil HTTPMethod:#"GET"] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
NSLog(#"result %#",result);
}];
Hope it helps you..

Swift 3.2 version of #Satish A answer.
func getPlaceId() {
let locManager = CLLocationManager()
locManager.requestWhenInUseAuthorization()
var currentLocation = CLLocation()
if( CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
CLLocationManager.authorizationStatus() == .authorizedAlways) {
currentLocation = locManager.location!
let param = ["center":"\(currentLocation.coordinate.latitude),\(currentLocation.coordinate.longitude)","type":"place","distance":"100"]
FBSDKGraphRequest(graphPath: "/search", parameters: param).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil) {
guard let data = result as? NSDictionary else {
return
}
guard let arrPlaceIDs = data.value(forKey: "data") as? [NSDictionary] else {
return
}
guard let firstPlace = arrPlaceIDs.first else {
return
}
//First facebook place id.
print(firstPlace.value(forKey: "id") as! String)
} else {
print(error?.localizedDescription ?? "error")
}
})
}
}
For Facebook sharing with attaching placeId
let photo = Photo(image: img, userGenerated: true)
var content = PhotoShareContent()
content.photos = [photo]
content.placeId = id //Facebook placeId
let sharer = GraphSharer(content: content)
sharer.failsOnInvalidData = true
do {
try sharer.share()
} catch {
print("errorrrr")
}
sharer.completion = { FBresult in
switch FBresult {
case .failed(let error):
print(error)
break
case .success(_):
//code
break
default:
break
}
}

You need to set the place (which is actually a Page ID) field within the POST request on /me/photos.
See https://developers.facebook.com/docs/graph-api/reference/v2.0/user/photos/#publish
On iOS, you can use the PlacePicker UI component of the FB iOS SDK for that, as described here: https://developers.facebook.com/docs/ios/ui-controls#placepicker

Related

Why iOS Facebook Signup Email id not returned in my account?

I'm using signup with Facebook. Other Facebook login works fine. Some accounts are working fine, but some accounts are not returning email. If anyone knows the reason please help me!
- (void)facebookOpenSession{
NSArray *permissions = [[NSArray alloc] initWithObjects:#"user_birthday",#"basic_info",#"user_location",#"user_likes",#"email",#"public_profile",#"user_hometown",#"user_about_me",nil];
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
logInWithReadPermissions: permissions
fromViewController:self.view.window.rootViewController
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error) {
} else if (result.isCancelled) {
} else {
if ([result.grantedPermissions containsObject:#"email"])
{
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me"
parameters:#{#"fields": #"picture, email,name,first_name,last_name"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
if ([result objectForKey:#"email"]!=NULL)
{
[self newFbLoginFunction:result];
}
}
}];
}
}
}];}
Response like this:
{
"first_name" = AAAA;
id = 1XXXXXXXXX2258;
"last_name" = BBBBB;
name = "AAAA BBBBB";
picture = {
data = {
"is_silhouette" = 0;
url = "https://fb-s-c-a.akamaihd.net/h-ak-xpa1/v/t1.0-1/p50x50/XXXXXXXXXXX3212_3395344935279367518_n.jpg?oh=7345e4de6XXXXXXXXXXXX8&oe=58E16A60&__gda__=14951668XXXXXXXXXX2bc0aec58eab3f25e47";
};
};}
Not all users use an email to login, you can also use a phone number. Also, emails need to be approved by Facebook or they will not show up with the API.
In other words: You can never guarantee to get an email back. Present an email input field to the user if you canĀ“t get the email with the API.

Share on facebook when app is not configured

I want post something on Facebook. I have used SLComposeViewController for that. I just want to ask how can i share if user hasn't configured its app in phone.
Is there any way that I open it in browser and then post anything. Consider I want to post any string say "hello there" . So i keep this string , open safari and login there . After I am logged in the string is posted automatically
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) {
let fbShare:SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
fbShare.completionHandler = {
result in
switch result {
case SLComposeViewControllerResult.Cancelled:
//Code to deal with it being cancelled
break
case SLComposeViewControllerResult.Done:
//Code here to deal with it being completed
break
}
}
refrenceViewController.presentViewController(fbShare, animated: true, completion: nil)
} else {
//open safari and post it there
}
I used the following code to post videos to facebook. You can use similar approach to post your text.
NSData *data = [NSData dataWithContentsOfURL:outputFileURL];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
data, #"video.mp4",
#"video/mp4", #"contentType",
caption, #"description",
nil];
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me/videos"
parameters:params
HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if(!error) {
DDLogDebug(#"result %#",result);
} else {
DDLogError(#"error description : %#",error.description);
[Helper showToast:[NSString stringWithFormat:#"Unable to share to Facebook : Error: %#",[error localizedDescription]] withDuration:1];
}
}];
of course before this you need to make sure that you already have the FBSDKAccess token granted. You can check the full documentation from facebook sdk
https://developers.facebook.com/docs/ios/graph

Facebook Live Video API, can I share a friend video stream programmatically?

I want to share a Facebook video live stream on my own wall programmatically. I want to do it inside my app after a Facebook login made with the facebook sdk, something like a normal link sharing:
NSMutableDictionary* params = [[NSMutableDictionary alloc] init];
[params setObject:link forKey:#"picture"];
[params setObject:LinkStringa forKey:#"link"];
[params setObject:ShareTextView.text forKey:#"message"];
[params setObject:[[FBSDKAccessToken currentAccessToken] tokenString] forKey:#"access_token"];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me/feed"
parameters:params
HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
// Handle the result
if (!error) {
}
else{
NSLog(#"error %#",error.description);
}
}];
I can't find mentions about sharing live video on Facebook documentation, only how create and publish live video. How can I share a live stream video?
You can use this method for that:
- (void)enableFacebookLiveStreamingWithCompletionHandler:(void(^)(NSString* facebookStreamURL, NSString* facebookStreamKey, NSError* error))completionHandler;
{
dispatch_async(dispatch_get_main_queue(), ^{
if ([[FBSDKAccessToken currentAccessToken] hasGranted:permissionPublishActions])
{
NSString* liveVideosRequestPath = [NSString stringWithFormat:#"/%#/live_videos",[FBSDKAccessToken currentAccessToken].userID];
FBSDKGraphRequest* request = [[FBSDKGraphRequest alloc] initWithGraphPath:liveVideosRequestPath parameters:nil HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
NSLog(#"%#",[FBSDKAccessToken currentAccessToken].permissions);
if (error)
{
if (completionHandler)
completionHandler(#"",#"",error);
}
else
{
if (completionHandler)
completionHandler(#"rtmp://rtmp-api.facebook.com:80/rtmp/",[[result objectForKey:#"stream_url"] lastPathComponent],nil);
}
}];
}
});
}
For streaming via RTMP use this open source library: https://github.com/jgh-/VideoCore
There is a code for example:
self.vcSession = [[VCSimpleSession alloc] initWithVideoSize:CGSizeMake(854, 480) frameRate:30 bitrate:1000000 useInterfaceOrientation:NO];
[self.view addSubview:self.vcSession.previewView];
self.vcSession.previewView.frame = CGRectMake(40, 40, 320, 240);//self.view.bounds;
self.vcSession.delegate = self;
[self.vcSession startRtmpSessionWithURL:#"your rtmp:URL "andStreamKey:#"your stream key"];
Swift 3
you can check this repo
https://github.com/hansemannn/facebook-live-ios
How to use
var liveVideo: FBSDKLiveVideo!
override func viewDidLoad() {
super.viewDidLoad()
// Create the live video service
liveVideo = FBSDKLiveVideo(
delegate: self,
previewSize: self.view.bounds,
videoSize: CGSize(width: 1280, height: 720)
)
// Optional: Configure the live-video (see the source for all options)
liveVideo.privacy = .me // or .friends, .friendsOfFriends, .custom
liveVideo.audience = "me" // or your user-id, page-id, event-id, group-id, ...
// Optional: Add the preview view of the stream to your container view.
myView.addSubView(liveVideo.preview)
}
Found this link https://developers.facebook.com/docs/videos/live-video-api which states:
" Stream a Live Video
Once a live_video object is created, a stream_url and key will be returned in the response. The server URL will be http://rtmp-api.facebook.com/rtmp/ and the stream key will be everything after it. Use both in order to push video frames through your streaming software."
Let me know how it turns out though as I'm also starting an app with this functionality.

How to get Facebook friends list using FBSDK for iOS?

I want to fetch the list of friends from facebook in my app. I'm able to get the total_friends correctly, but the list of friends is not coming in the result.
My current code that is not working:
CODE:
NSMutableString *facebookRequest = [NSMutableString new];
[facebookRequest appendString:#"/me/friends"];
[facebookRequest appendString:#"?limit=100"];
NSDictionary *friendParams = #{#"fields" : #"name"};
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"/me/friends"
parameters:friendParams
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
//my code here
}
OUTPUT:
{
data = (
);
summary = {
"total_count" = 661;
};
}
I'm using Xcode 7.1
I used similar methods but my code is in swift. Your friends list are their but you don't get the name for that u have to create an array. And put all the result of your friends into that array. and display it wherever you want to show.
Here is the code for Facebook friends in swift:
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me/friends", parameters: ["fields": "id,name,picture"])
graphRequest.startWithCompletionHandler( { (connection, result, error) -> Void in
if ((error) != nil)
{
print("Error: \(error)")
return
}
else
{
let friends = result.valueForKey("data") as! NSArray
var count = 1
if let array = friends as? [NSDictionary] {
for friend : NSDictionary in array {
let name = friend.valueForKey("name") as! String
frindsFromGlobal.append(name)
count++
}
}
}
From v2.0 /me/friends will only return the friends who are using your app.
So in your case the app that you have created in developer.facebook.com is not authorised or used by any of your friends
Also you must request the user_friends permission from each user

How to fetch user's birthday from Facebook API in iOS using latest Facebook sdk?

How to fetch user's birthday from Facebook API in iOS using latest Facebook sdk?
I have tried to fetch it
{#"fields": #"id, name, link, first_name, last_name, picture.type(large), email, birthday"}
and have given permission
[login logInWithReadPermissions:#[#"public_profile", #"email", #"user_friends",#"user_birthday"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
But not able the fetch birthday.
You can't fetch users birthdate only yours you can get and you have to send app in review for approve in facebook developer after than if your app approve than you can set extra permissions but i don't think that users birthday you can get.
Use this code.This may help you
(IBAction)btnfb:(id)sender
{
if (!FBSession.activeSession.isOpen)
{
NSArray *_fbPermissions = #[#"email",#"publish_actions",#"public_profile",#"user_hometown",#"user_birthday",#"user_about_me",#"user_friends",#"user_photos",];
[FBSession openActiveSessionWithReadPermissions:_fbPermissions allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState state, NSError *error)
{
if (error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else if(session.isOpen)
{
[self btn_fb:sender];
}
}];
return;
}
[FBRequestConnection startWithGraphPath:#"me" parameters:[NSDictionary
dictionaryWithObject:#"cover,picture.type(large),id,name,first_name,last_name,gender,birthday,email,location,hometown,bio,photos"
forKey:#"fields"] HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection, id result, NSError
*error)
{
{
if (!error)
{
if ([result isKindOfClass:[NSDictionary class]])
{
NSLog(#"%#",result);
}
}
}
}];
}
Swift 3x:
Hope this will help anybody
//MARK: - sign in with facebook
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.logIn(withReadPermissions: ["email","user_photos","user_birthday"], from: self) { (result, error) -> Void in
if (error == nil) {
let fbloginresult : FBSDKLoginManagerLoginResult = result!
print("fbloginresult######:\(fbloginresult)")
if (result?.isCancelled)! {
print(result ?? FBSDKLoginManagerLoginResult())
} else if(fbloginresult.grantedPermissions.contains("email")) {
//show loader
//print(user())
//FETCH USER DATA
if((FBSDKAccessToken.current()) != nil) {
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email, birthday"]).start( completionHandler: { (connection, result, error) -> Void in
if (error == nil) {
//everything works print the user data
print(result ?? AnyObject.self)
if let jsondata = result as? [String: Any], let strEmail = jsondata["email"] as? String, let fb_id = jsondata["id"] as? String, let picture = jsondata["picture"] as? [String: Any], let data = picture["data"] as? [String: Any],let url = data["url"] as? String {
// print(url)
print(strEmail)
print(fb_id)
}
//Loader hide
}
})
}
}
}
}
Try the account in which you have registered your app. Don't try with other Facebook account.
It will give you a Birhtday.
Also check privacy settings of account.
Birthday may not be public. That can also be an issue.
Thanks
Take in account that to get the birthday (and some other attributes like the user bio) the app has to be reviewed by Facebook. Otherwise, although the permissions were given correctly to the user the Graph API call will not retrieve this attribute.

Resources