Share videos on Twitter via iOS App - ios

Is it possible to share a video using SLRequest ?
I'm able to share Images using the same
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:requestURL parameters:message];
if (isImage)
{
NSData *data = UIImagePNGRepresentation(imgSelected);
[postRequest addMultipartData:data withName:#"media" type:#"image/png" filename:#"TestImage.png"];
}
postRequest.account = account;
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if (!error)
{
NSLog(#"Upload Sucess !");
}
}];

I have been reading through the Twitter Video upload API documentation and its really pretty simple. You basically need to make 3 POST requests to their API. The video you are uploading is also limited to 15 MB in size.
Uploads using this endpoint require at least 3 calls, one to
initialize the request, which returns the media_id, one or more calls
to append/upload binary or base64 encoded data, and one last call to
finalize the upload and make the media_id usable with other resources.
So it works like this:
Request 1: Send a init request with the video size in bytes. This will return a Media ID number which we have to use in request 2 and 3.
Request 2: Use the returned Media ID number from request 1 to upload the video data.
Request 3: Once the video upload has finished, send a "FINALIZE" request back to the Twitter API. This lets the Twitter API know that all the chunks of the video file has finished uploading.
Note The Twitter API accepts video uploads in "chunks". So if your video file is quite big, you may want to split it up into more than one file and thus you will have to repeat "Request 2" more than once (not forgetting to increment the "segment_index" number each time).
I have had a go at coding this below. Try it and experiment around with it. I will update my answer later on to improve it too.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
// Assign the mediatype to a string
NSString *mediaType = [info objectForKey:UIImagePickerControllerMediaType];
// Check the media type string so we can determine if its a video
if ([mediaType isEqualToString:#"public.movie"]) {
NSURL *videoURL = [info objectForKey:UIImagePickerControllerMediaURL];
NSData *webData = [NSData dataWithContentsOfURL:videoURL];
// Get the size of the file in bytes.
NSString *yourPath = [NSString stringWithFormat:#"%", videoURL];
NSFileManager *man = [NSFileManager defaultManager];
NSDictionary *attrs = [man attributesOfItemAtPath:yourPath error: NULL];
UInt32 result = [attrs fileSize];
//[self tweetVideoStage1:webData :result];
[self tweetVideo:webData :result :1 :#"n/a"];
}
}
-(void)tweetVideo:(NSData *)videoData :(int)videoSize :(int)mode :(NSString *)mediaID {
NSURL *twitterVideo = [NSURL URLWithString:#"https://upload.twitter.com/1.1/media/upload.json"];
// Set the parameters for the first twitter video request.
NSDictionary *postDict;
if (mode == 1) {
postDict = #{#"command": #"INIT",
#"total_bytes" : videoSize,
#"media_type" : #"video/mp4"};
}
else if (mode == 2) {
postDict = #{#"command": #"APPEND",
#"media_id" : mediaID,
#"segment_index" : #"0",
#"media" : videoData };
}
else if (mode == 3) {
postDict = #{#"command": #"FINALIZE",
#"media_id" : mediaID };
}
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:requestURL:twitterVideo parameters:postDict];
// Set the account and begin the request.
postRequest.account = account;
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (!error) {
if (mode == 1) {
// Parse the returned data for the JSON string
// which contains the media upload ID.
NSMutableDictionary *returnedData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableContainers error:&error]
NSString *tweetID = [NSString stringWithFormat:#"%#", [returnedData valueForKey:#"media_id_string"]];
[self tweetVideo:videoData :result :2 :tweetID];
}
else if (mode == 2) {
[self tweetVideo:videoData :result :3 :mediaID];
}
}
else {
NSLog(#"Error stage %d - %", mode, error);
}
}];
}
Update - Twitter API errors - https://dev.twitter.com/overview/api/response-codes
In answer to your first comment, error 503 means that the Twitter servers are overloaded and can't handle your request right now.
503 Service Unavailable The Twitter servers are up, but overloaded
with requests. Try again later.

I know how to upload video to twitter use the new API. And I have tried it, it works.
Please check this: https://github.com/liu044100/SocialVideoHelper
You just need to call this class method.
+(void)uploadTwitterVideo:(NSData*)videoData account:(ACAccount*)account withCompletion:(dispatch_block_t)completion;
Hope it can resolve your problem.
Best Regards.

Been looking for sharing video on Twitter solution with below features:
Support chunk upload
Built-in support for user's credential retrieval
Since I couldn't find one meeting my need, so I decided to write one.
https://github.com/mtrung/TwitterVideoUpload
I've been testing for awhile now and it works well for me.
Hope it helps,
Regards.

Try this based in #Dan answer. It not tested, but I think it can work.
Use Cocoa-pods: pod 'TwitterKit'
if you don't use Pods try with fabric
//for Extern call
//Mode is 1
//MediaId is 0
- (void)uploadTwitterVideo:(NSData*)videoData videoTitle:(NSString *)title desc:(NSString *)desc withMode:(int)mode mediaID:(NSString *)mediaID withCompletion:(dispatch_block_t)completion
{
NSString *twitterPostURL = #"https://upload.twitter.com/1.1/media/upload.json";
NSDictionary *postParams;
if (mode == 1) {
postParams = #{#"command": #"INIT",
#"total_bytes" : [NSNumber numberWithInteger: videoData.length].stringValue,
#"media_type" : #"video/mp4"};
} else if (mode == 2) {
postParams = #{#"command": #"APPEND",
#"media_id" : mediaID,
#"segment_index" : #"0"};
} else if (mode == 3) {
postParams = #{#"command": #"FINALIZE",
#"media_id" : mediaID };
} else if (mode == 4) {
postParams = #{#"status": desc,
#"media_ids" : #[mediaID]};
}
TWTRAPIClient *twitterInstance = [[Twitter sharedInstance] APIClient];
NSError *error;
NSURLRequest *requestTw = [twitterInstance URLRequestWithMethod:#"POST" URL:twitterPostURL parameters:postParams error:&error];
[twitterInstance sendTwitterRequest:requestTw completion:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
NSLog(#"HTTP Response: %li, responseData: %#", (long)response, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
if (error) {
NSLog(#"There was an error:%#", [error localizedDescription]);
} else {
if (mode == 1) {
NSMutableDictionary *returnedData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&connectionError];
NSString *mediaIDResponse = [NSString stringWithFormat:#"%#", [returnedData valueForKey:#"media_id_string"]];
NSLog(#"stage one success, mediaID -> %#", mediaID);
[self uploadTwitterVideo:videoData videoTitle:title desc:desc withMode:2 mediaID:mediaIDResponse withCompletion:completion];
} else if (mode == 2) {
[self uploadTwitterVideo:videoData videoTitle:title desc:desc withMode:3 mediaID:mediaID withCompletion:completion];
} else if (mode == 3) {
[self uploadTwitterVideo:videoData videoTitle:title desc:desc withMode:4 mediaID:mediaID withCompletion:completion];
} else if (mode == 4) {
DispatchMainThread(^(){completion();});
}
}
}];
}
This API Works as follows.
- Login when application (twitter) is installed and when is not installed
- First priority take credential from setting
Check this case

Swift
Its very Simple.
First you need to sign in to your Twitter Account. Go to Phone Setting and click on twitter app and sign in.
Now Just Call this videoUpload func anywhere
Video or Chunked uploads Method Reference
Replace your video type/extension on that code
And Carefully read all twitter requirements.
var twitterAccount = ACAccount()
func videoUpload{
let path = Bundle.main.path(forResource: "file-Name", ofType:"mp4")
let filePath = path
var fileSize = UInt64()
do {
//return [FileAttributeKey : Any]
let attr = try FileManager.default.attributesOfItem(atPath: filePath!)
fileSize = attr[FileAttributeKey.size] as! UInt64
//if you convert to NSDictionary, you can get file size old way as well.
let dict = attr as NSDictionary
fileSize = dict.fileSize()
} catch {
print("Error: \(error)")
}
let accountStore = ACAccountStore()
let twitterAccountType = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccounts(with: twitterAccountType, options: nil) { (granted, error) in
if granted {
let accounts = accountStore.accounts(with: twitterAccountType)
if (accounts?.count)! > 0 {
self.twitterAccount = accounts?.last as! ACAccount
}}}
twitterAccount = Twitter.sharedInstance().sessionStore.session() as! ACAccount
uploadVideoToTwitter(videoURL: URL(string : path!)! as NSURL, fileSize: UInt32(fileSize))
}
func uploadVideoToTwitter(videoURL:NSURL,fileSize: UInt32) {
if let videoData = NSData(contentsOfFile: videoURL.path!){
self.tweetVideoInit(videoData: videoData, videoSize: Int(fileSize))
}
}
func tweetVideoInit(videoData:NSData,videoSize:Int) {
let uploadURL = NSURL(string:"https://upload.twitter.com/1.1/media/upload.json")
var params = [String:String]()
params["command"] = "INIT"
params["total_bytes"] = String(videoData.length)
params["media_type"] = "video/mp4"
let postRequest = SLRequest(forServiceType: SLServiceTypeTwitter,
requestMethod: SLRequestMethod.POST,
url: uploadURL as URL!,
parameters: params)
postRequest?.account = self.twitterAccount;
postRequest?.perform(handler: { ( responseData, urlREsponse,error) in
if let err = error {
print(error as Any)
}else{
do {
let object = try JSONSerialization.jsonObject(with: responseData! as Data, options: .allowFragments)
if let dictionary = object as? [String: AnyObject] {
if let tweetID = dictionary["media_id_string"] as? String{
self.tweetVideoApped(videoData: videoData, videoSize: videoSize, mediaId: tweetID, chunk: 0)
}
}
}
catch {
print(error)
}
}
})
}
func tweetVideoApped(videoData:NSData,videoSize:Int ,mediaId:String,chunk:NSInteger) {
let uploadURL = NSURL(string:"https://upload.twitter.com/1.1/media/upload.json")
var params = [String:String]()
params["command"] = "APPEND"
params["media_id"] = mediaId
params["segment_index"] = String(chunk)
let postRequest = SLRequest(forServiceType: SLServiceTypeTwitter,
requestMethod: SLRequestMethod.POST,
url: uploadURL as URL!,
parameters: params)
postRequest?.account = self.twitterAccount
postRequest?.addMultipartData(videoData as Data!, withName: "media", type: "video/mov", filename:"mediaFile")
postRequest?.perform(handler: { ( responseData, urlREsponse,error) in
if let err = error {
print(err)
}else{
self.tweetVideoFinalize(mediaId: mediaId)
}
})
}
func tweetVideoFinalize(mediaId:String) {
let uploadURL = NSURL(string:"https://upload.twitter.com/1.1/media/upload.json")
var params = [String:String]()
params["command"] = "FINALIZE"
params["media_id"] = mediaId
let postRequest = SLRequest(forServiceType: SLServiceTypeTwitter,
requestMethod: SLRequestMethod.POST,
url: uploadURL as URL!,
parameters: params)
postRequest?.account = self.twitterAccount;
postRequest?.perform(handler: { ( responseData, urlREsponse,error) in
if let err = error {
print(err)
}else{
do {
let object = try JSONSerialization.jsonObject(with: responseData! as Data, options: .allowFragments)
if let dictionary = object as? [String: AnyObject] {
self.postStatus(mediaId: mediaId)
}
}
catch {
print(error)
}
}
})
}
func postStatus(mediaId:String) {
let uploadURL = NSURL(string:"https://api.twitter.com/1.1/statuses/update.json")
var params = [String:String]()
params["status"] = "my first Video Upload"
params["media_ids"] = mediaId
let postRequest = SLRequest(forServiceType: SLServiceTypeTwitter,
requestMethod: SLRequestMethod.POST,
url: uploadURL as URL!,
parameters: params)
postRequest?.account = self.twitterAccount;
postRequest?.perform(handler: { ( responseData, urlREsponse,error) in
if let err = error {
print(err)
}else{
do {
let object = try JSONSerialization.jsonObject(with: responseData! as Data, options: .allowFragments)
if let dictionary = object as? [String: AnyObject] {
print("video uploaded")
}
}
catch {
print(error)
}
}
})
}

I was able to upload video to twitter successfully!
Below are steps referred from twitter docs:
Request for twitter account
accountStore.requestAccessToAccounts(with: twitterAccountType,options:nil){(granted, error) in
POST media/upload (INIT)
params["command"] = "INIT"
params["total_bytes"] = String(videoData.length)
params["media_type"] = "video/mov"
POST media/upload (APPEND)
params["command"] = "APPEND"
params["media_id"] = mediaId
params["segment_index"] = String(chunk)
POST media/upload (FINALIZE)
params["command"] = "FINALIZE"
params["media_id"] = mediaId
POST media/upload
params["status"] = twitterDescription
params["media_ids"] = mediaId
Here is twitter doc link https://dev.twitter.com/rest/media/uploading-media.html
Please fine the detailed solution for video upload to twitter using SLRequest here.
http://swiftoverflow.blogspot.in/2017/04/upload-video-to-twitter-using-slrequest.html

Related

Making an HTTP POST request swift with session

I try do POST request to backend server and use this for base session inside of a class "ServiceUtils" in objective - c
(AFHTTPSessionManager *)baseSessionManager {
if (httpSessionManager) {
return httpSessionManager;
}
httpSessionManager = [AFHTTPSessionManager manager];
httpSessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
[httpSessionManager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[httpSessionManager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Accept"];
// User agent for iOS app.
NSString *userAgent = [NSString stringWithFormat:#"xxxxx Mobile iOS/%# (%# - %# v%#)", [Utils appVersionWithBuild], [[UIDevice currentDevice] model], [[UIDevice currentDevice] systemName], [[UIDevice currentDevice] systemVersion]];
[httpSessionManager.requestSerializer setValue:userAgent forHTTPHeaderField:#"User-Agent"];
// Mobile auth
User *user = [User getUserWithContext:[NSManagedObjectContext MR_defaultContext]];
NSString *mobileAuth = [[NSString stringWithFormat:#"%#--givemymoneybackdude", user.token] sha1];
[httpSessionManager.requestSerializer setValue:mobileAuth forHTTPHeaderField:#"Mobile-Auth"];
// Authorization
NSString *authorization = [[NSString stringWithFormat:#"%#:X", user.token] stringBase64];
[httpSessionManager.requestSerializer setValue:[NSString stringWithFormat:#"Basic %#", authorization] forHTTPHeaderField:#"Authorization"];
// Locale
if (user.locale) {
[httpSessionManager.requestSerializer setValue:user.locale forHTTPHeaderField:#"Accept-Language"];
}
return httpSessionManager;
}
Here is my code to try make POST request in swift 2.3
if let url = NSURL(string: "xxxxxxxx") {
let session = ServicesUtils.baseSessionManager()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
let jsonObject = ["token" : "Token String", "refresh_token" : "refresh_token String","expires_in" : "expires_in String", "user_id" : "uber_uuid", "token_type" : "Bearer"]
request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(jsonObject, options: [])
session.dataTaskWithRequest(request) { data, response, error in
guard
error == nil &&
(response as? NSHTTPURLResponse)?.statusCode == 200
else {
print((response as? NSHTTPURLResponse)?.statusCode ?? "no status code")
print(error?.localizedDescription ?? "no error description")
return
}
}.resume()
After try this i get this error :
Request failed: unauthorized (401)
I checked the header and it is ok but this problem is occurring. Can someone tell me why it's happening? And how could I pass inside a jsonObject a dictionary called "Integration" containing the values in it
This Code will help You…And using Alamofire.
Alamofire.request(requestUrl, method: .post, parameters: (parametersDictionary as NSDictionary) as? Parameters , encoding: JSONEncoding.default, headers: nil).responseJSON { response in
if(response.result.error == nil){
if((response.response?.statusCode)! < 500){
if(response.response?.statusCode == 200){
if let JSON = response.result.value {
let dict = JSON as! NSDictionary
let status :Bool = dict["status"] as! Bool
if(status){
success(dict)
}else{
failure(dict["message"] as! String)
}
}
}else{
failure("Something went wrong please try again")
}
}else{
failure("Something went wrong please try again")
}
}
}
}
I hope the following Link will may help you: https://github.com/Alamofire/Alamofire

Can't get result from NSURL

I'm trying to read remote txt file, which is located at remote hosting. I have a link, like http://www.link.com/file.txt.
I am using this code:
let myURLString = "http://google.com"
guard let myURL = NSURL(string: myURLString) else {
print("Error: \(myURLString) doesn't seem to be a valid URL")
return
}
do {
let myHTMLString = try String(contentsOfURL: myURL)
print("HTML : \(myHTMLString)")
} catch let error as NSError {
print("Error: \(error)")
}
But always getting empty string. File is not empty for sure.
I'm running my app on iOS simulator in Xcode.
What am I doing wrong?
Sorry for my bad English.
Don't use stringWithContentsOfURL and friends to retrieve data from a remote server. That's a synchronous API that was designed solely for use with local files. It isn't even guaranteed to work right for network requests on background threads, much less in your main thread.
The right way to retrieve data from remote URLs is with NSURLSession. I'm not a Swift programmer, so I'm not going to attempt a Swift snippet, but the Objective-C equivalent is:
NSURL *url = ...
NSURLSessionDataTask *task =
[NSURLSession sharedSession dataTaskWithURL:url
completionHandler:^(NSData *data,
NSURLResponse *response,
NSError *error) {
if (error) {
// Handle client-side errors here
} else if (((NSHTTPURLResponse *)response).statusCode != 200) {
// Handle server-side errors here
} else {
NSString *stock = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
// Do something with data here.
}
}];
[task resume];
Haven't test the code, but this should lead you on the right direction.
var statsRequest: String = "http://www.link.com/file.txt"
var statsRequestURL: NSURL = NSURL(string: statsRequest)!
var error: NSError? = nil
var stockNews: String = try! String.stringWithContentsOfURL(statsRequestURL, encoding: NSUTF8StringEncoding)
If the text file has a different encoding you can just use NSASCIIStringEncoding and then parse the html file.

get all the tracks from playlist Spotify

I was able to get all the playlist of users using spotify ios sdk, this is my code.
[SPTPlaylistList playlistsForUserWithSession:session callback:^(NSError *error, id object) {
SPTListPage *pl= object;
NSLog(#"%#",pl.items);
}];
But I am not sure now How to get all the tracks of these playlists. any help?
Because this Spotify ios SDK v10beta is new and with many incomplete tasks, to access and be able to play all tracks in your playlists you have to run through many blocks.
First I would recommend to get the first SPTListPage object of all the playlists:
-(void)getFirstPlaylistPage
{
[SPTPlaylistList playlistsForUserWithSession:[SPTAuth defaultInstance].session callback:^(NSError *error, SPTListPage *playlistsPage) {
if (error != nil) {
NSLog(#"*** Getting playlists got error: %#", error);
return;
}
if (playlistsPage==nil) {
NSLog(#"*** No playlists were found for logged in user. ***");
return;
}
[self getFullPlaylistPage:playlistsPage];
}];
}
Then, merge all SPTListPage objects into one:
-(void)getFullPlaylistPage:(SPTListPage*)listPage {
if (listPage.hasNextPage) {
[listPage requestNextPageWithSession:[SPTAuth defaultInstance].session callback:^(NSError *error, SPTListPage* playlistPage) {
if (error != nil) {
NSLog(#"*** Getting playlist page got error: %#", error);
return;
}
listPage = [listPage pageByAppendingPage:playlistPage];
[self getFullPlaylistPage:listPage];
}];
} else {
NSMutableArray* playlist = [[NSMutableArray alloc]init];
[self convertPlaylists:listPage arrayOfPlaylistSnapshots:playlist positionInListPage:0];
}
}
Now, SPTListPage contains SPTPartialPlaylist objects, which do not contain all the info of the playlists, so we need to convert it to SPTPlaylistSnapshot object:
-(void)convertPlaylists:(SPTListPage*)playlistPage arrayOfPlaylistSnapshots:(NSMutableArray*)playlist positionInListPage:(NSInteger)position
{
if (playlistPage.items.count > position) {
SPTPartialPlaylist* userPlaylist = playlistPage.items[position];
[SPTPlaylistSnapshot playlistWithURI:userPlaylist.uri session:[SPTAuth defaultInstance].session callback:^(NSError *error, SPTPlaylistSnapshot* playablePlaylist) {
if (error != nil) {
NSLog(#"*** Getting playlists got error: %#", error);
return;
}
if(!playablePlaylist){
NSLog(#"PlaylistSnapshot from call back is nil");
return;
}
[playlist addObject:playablePlaylist];
[self convertPlaylists:playlistPage arrayOfPlaylistSnapshots:playlist positionInListPage:position+1];
}];
} else {
// send your array of playlists somewhere example:
[self addSongs];
}
}
Now you can access all the playlists and all the songs in them with a simple loop-through.
I hope spotify will improve here as it is not how it supposed to be. Come on,Spotify!
Using Swift3:
After authentication, define a playlist request , like this:
let playListRequest = try! SPTPlaylistList.createRequestForGettingPlaylists(forUser: userName, withAccessToken: token)
I use alamofire to post this request:
Alamofire.request(playListRequest)
.response { response in
let list = try! SPTPlaylistList(from: response.data, with: response.response)
for playList in list.items {
if let playlist = playList as? SPTPartialPlaylist {
print( playlist.name ) // playlist name
print( playlist.uri) // playlist uri
let stringFromUrl = playlist.uri.absoluteString
let uri = URL(string: stringFromUrl)
// use SPTPlaylistSnapshot to get all the playlists
SPTPlaylistSnapshot.playlist(withURI: uri, accessToken: token!) { (error, snap) in
if let s = snap as? SPTPlaylistSnapshot {
// get the tracks for each playlist
print(s.name)
for track in s.firstTrackPage.items {
if let thistrack = track as? SPTPlaylistTrack {
print(thistrack.name)
}
}
}
}
}
}
}

How to post location with image to facebook in 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

Facebook Integration Error ( Accounts.framework) in iOS6

I am using the following code (showed on WWDC 2012 videos):
self.accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookAccountType = [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[self.accountStore requestAccessToAccountsWithType:facebookAccountType
withCompletionHandler:^(BOOL granted, NSError *e) {
if (granted)
{
NSArray *accounts = [self.accountStore
accountsWithAccountType:facebookAccountType];
self.facebookAccount = [accounts lastObject];
} else {
// Fail gracefully...
}
}];
I have also added the NSDictionary to my .plist file:
So, my problem is that I am receiving the following exception:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Access options are required for this account type.'
I have tried with this ACAccountTypeIdentifierTwitter and ACAccountTypeIdentifierSinaWeibo. I am not receiving any exception although they are always returning granted == NO
Well, the WWDC 2012 shows one thing, but the documentation shows another... The method they are using is now deprecated:
– requestAccessToAccountsWithType:withCompletionHandler: Deprecated in iOS 6.0
What you should do:
ACAccountType *facebookAccountType = [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSDictionary *options = #{
#"ACFacebookAppIdKey" : #"123456789",
#"ACFacebookPermissionsKey" : #[#"publish_stream"],
#"ACFacebookAudienceKey" : ACFacebookAudienceEveryone}; // Needed only when write permissions are requested
[self.accountStore requestAccessToAccountsWithType:facebookAccountType options:options
completion:^(BOOL granted, NSError *error) {
if (granted)
{
NSArray *accounts = [self.accountStore
accountsWithAccountType:facebookAccountType];
self.facebookAccount = [accounts lastObject];
} else {
NSLog(#"%#",error);
// Fail gracefully...
}
}];
Swift 3
let account = ACAccountStore()
let accountType = account.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierFacebook)
let options: [AnyHashable : Any] = [ACFacebookAppIdKey: "Your App ID on FB", ACFacebookPermissionsKey: ["publish_stream", "publish_actions"], ACFacebookAudienceKey: ACFacebookAudienceEveryone]
account.requestAccessToAccounts(with: accountType, options: options) { (success, error) in
if success {
if let accounts = account.accounts(with: accountType) {
if accounts.isEmpty {
print("No facebook account found, please add your facebook account in phone settings")
} else {
let facebookAccount = accounts.first as! ACAccount
let message = ["status": "My first Facebook posting "]
let requestURL = URL(string: "https://graph.facebook.com/me/feed")
let postRequest = SLRequest(forServiceType: SLServiceTypeFacebook,
requestMethod: SLRequestMethod.POST,
url: requestURL,
parameters: message)
postRequest?.account = facebookAccount
postRequest?.perform(handler: {(_, urlResponse,
error) in
if let err = error {
print("Error : \(err.localizedDescription)")
}
print("Facebook HTTP response \(String(describing: urlResponse?.statusCode))")
})
}
}
} else {
print("Facebook account error: \(String(describing: error))")
}
}

Resources