Change FBSession with page access token to publish post on fb page as admin - facebook-graph-api

I want to publish a post as admin in a facebook page where the user is admin of the page.
I have the page access token from
[FBRequestConnection startWithGraphPath:#"/me/accounts"
parameters:nil
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
NSString *token = [[[result objectForKey:#"data"] objectAtIndex:0] objectForKey:#"access_token"];//accessToken of the page
}];
Now how can i change the FBSession with this token to publish a post on the page as an admin using GraphAPI? FBDocumentation refers to this for openFromAccessTokenData . Please help as i m stuck with this for long time. I m using facebook sdk 3.2. Thanks in advance

NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:token, #"access_token",
titleCell.titleTextView.text,#"message",
[UserDefaultsManager fbPlaceId], #"place",
// fbPhotoId,#"object_attachment",
#"https://www.google.com",#"link",
photoUrl,#"picture",
titleCell.titleTextView.text,#"name",
typeCell.cellTextField.text,#"caption",
descriptionCell.descriptionTextView.text,#"description",
nil];
FBRequest *requestToPost = [[FBRequest alloc] initWithSession:nil
graphPath:#"/me/feed"
parameters:param
HTTPMethod:#"POST"];
FBRequestConnection *requestToPostConnection = [[FBRequestConnection alloc] init];
[requestToPostConnection addRequest:requestToPost completionHandler:^(FBRequestConnection *connection, id result, NSError *error){
if(!error)
{
NSLog(#"facebook result >> %#", result);
NSData *photoData = UIImagePNGRepresentation(promoImage);
NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:token,#"access_token",
photoData,#"source", nil];
FBRequest *requestToPostPhoto = [[FBRequest alloc] initWithSession:nil
graphPath:#"/me/photos"
parameters:param
HTTPMethod:#"POST"];
FBRequestConnection *requestToPostPhotoConnection = [[FBRequestConnection alloc] init];
[requestToPostPhotoConnection addRequest:requestToPostPhoto completionHandler:^(FBRequestConnection *connection, id result, NSError *error){
if(!error)
{
[loadingAlert dismissWithClickedButtonIndex:0 animated:YES];
NSLog(#"facebook result photo>> %#", result);
doneAlert = [[UIAlertView alloc] initWithTitle:#"Success"
message:#""
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
if(self.isUpdatingPromo)
{
doneAlert.message = #"Promo updated successfully";
[doneAlert show];
}
else
{
doneAlert.message = #"Promo created successfully";
[doneAlert show];
}
}
else
{
[loadingAlert dismissWithClickedButtonIndex:0 animated:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Could not post photo"
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}
}];
[requestToPostPhotoConnection start];
}
else
{
[loadingAlert dismissWithClickedButtonIndex:0 animated:YES];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Could not post"
delegate:nil
cancelButtonTitle:#"Dismiss"
otherButtonTitles:nil];
[alert show];
}
}];
[requestToPostConnection start];

Related

PHImageManager.default().requestAVAsset for video

i have an big problem with my situation
my main problem is i need fetch video one by one do some operation on the video name and save it to the file system and again fetch another video do some operation on the video name and save it to the file system through the loop of asset the problem is completion handler prevent me do that because it saving all videos together without i do any editing and changing the name this save all videos i think it is working on background thread please any help to fix this problem i need handle fetch video one by one
this is my code
for asset in arrayOfAssets {
if asset.mediaType == .video {
PHImageManager.default().requestAVAsset(forVideo: asset, options: nil, resultHandler: { (AVAsset, AVAudio, info) in
// i need access to this place so i can fetch the video one by one and working with the AVAsset
})
}else{
let imageOp = PHImageRequestOptions()
PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width:125,height:125), contentMode: .aspectFit, options: imageOp, resultHandler: { (img, info) in
print(img!)
})
}
}
i think this one is related to your query
for Vedios
How Can i Get the List of all Video files from Library in ios sdk
for Images
Get all of the pictures from an iPhone photoLibrary in an array using AssetsLibrary framework?
allVideos = [[NSMutableArray alloc] init];
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
[assetLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop)
{
if (group)
{
[group setAssetsFilter:[ALAssetsFilter allVideos]];
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop)
{
if (asset)
{
dic = [[NSMutableDictionary alloc] init];
ALAssetRepresentation *defaultRepresentation = [asset defaultRepresentation];
NSString *uti = [defaultRepresentation UTI];
NSURL *videoURL = [[asset valueForProperty:ALAssetPropertyURLs] valueForKey:uti];
NSString *title = [NSString stringWithFormat:#"video %d", arc4random()%100];
UIImage *image = [self imageFromVideoURL:videoURL];
[dic setValue:image forKey:#"image"];
[dic setValue:title forKey:#"name"];
[dic setValue:videoURL forKey:#"url"];
[`allVideos` addObject:dic];
}
}];
else
{
}
}
failureBlock:^(NSError *error)
{
NSLog(#"error enumerating AssetLibrary groups %#\n", error);
}];
--------for ALL PHOTOS
NSArray *imageArray;
NSMutableArray *mutableArray;
-(void)getAllPhotosFromCamera
{
imageArray=[[NSArray alloc] init];
mutableArray =[[NSMutableArray alloc]init];
PHImageRequestOptions *requestOptions = [[PHImageRequestOptions alloc] init];
requestOptions.resizeMode = PHImageRequestOptionsResizeModeExact;
requestOptions.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
requestOptions.synchronous = true;
PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:nil];
NSLog(#"%d",(int)result.count);
PHImageManager *manager = [PHImageManager defaultManager];
NSMutableArray *images = [NSMutableArray arrayWithCapacity:[result count]];
// assets contains PHAsset objects.
__block UIImage *ima;
for (PHAsset *asset in result) {
// Do something with the asset
[manager requestImageForAsset:asset
targetSize:PHImageManagerMaximumSize
contentMode:PHImageContentModeDefault
options:requestOptions
resultHandler:^void(UIImage *image, NSDictionary *info) {
ima = image;
[images addObject:ima];
}];
}
imageArray = [images copy]; // You can direct use NSMutuable Array images
}

AWSSignInProvider for OpenID using Mobile Hub

I have an iOS 7 app that uses AWS Mobile Hub for AWS services. I am using Auth0 as an identity broker. All of my users authenticate using OpenID.
In order to use Mobile Hub I have to define an AWSSignInProvider for Auth0 users. Has anyone written a (possibly generic?) AWSSignInProvider in Objective C for OpenID users? I have written one but it does not work correctly. It works for the initial login but does not refresh the Auth0 login for Auth0 users when they re-login to my app.
My code is below. It does not work right.
Thanks
Auth0SignInProvider.h
#import <Foundation/Foundation.h>
#import <Lock/Lock.h>
#import "AWSSignInProvider.h"
#class FFKeyChain;
#pragma clang assume_nonnull begin
#interface FFAuth0SignInProvider : NSObject <AWSSignInProvider>
#property (readonly, strong) FFKeyChain * keychain;
+ (instancetype)sharedInstance;
- (void)completeLogin;
#end
#pragma clang assume_nonnull end
Auth0SignInProvider.m
#import "Auth0SignInProvider.h"
#import <Lock/Lock.h>
#import "AWSIdentityManager.h"
#import "AWSConfiguration.h"
#import "Cloud.h"
#import "FFCloudController.h"
#import "FFJWT.h"
#import "FFKeyChain.h"
static NSString *const AWSAuth0SignInProviderKey = #"Auth0";
static NSString *const AWSAuth0SignInProviderUserNameKey = #"Auth0.userName";
static NSString *const AWSAuth0SignInProviderImageURLKey = #"Auth0.imageURL";
static NSTimeInterval const AWSAuth0SignInProviderTokenRefreshBuffer = 10 * 60;
#interface AWSIdentityManager()
- (void)completeLogin;
#end
#interface FFAuth0SignInProvider()
#property (atomic, strong) AWSTaskCompletionSource *taskCompletionSource;
#property (nonatomic, strong) dispatch_semaphore_t semaphore;
#end
#implementation FFAuth0SignInProvider
#synthesize keychain=_keychain;
+ (instancetype)sharedInstance {
static FFAuth0SignInProvider *_sharedInstance = nil;
static dispatch_once_t onceToken;
//ok1
dispatch_once(&onceToken, ^{
_sharedInstance = [FFAuth0SignInProvider new];
});
return _sharedInstance;
}
- (instancetype)init {
if (self = [super init])
{
_keychain = [FFKeyChain sharedInstance];
}
return self;
}
#pragma mark - Properties
- (FFKeyChain*)keychain
{
if (!_keychain)
{
_keychain = [FFKeyChain sharedInstance];
}
return _keychain;
}
#pragma mark - AWSIdentityProvider Protocol
- (NSString *)identityProviderName
{
return [[NSBundle mainBundle] infoDictionary][STRAuth0DomainKey];
}
- (AWSTask<NSString *> *)token
{
NSString* tokenString = [[self keychain] stringForKey:UDAuth0IdToken];
NSString* refreshToken = [[self keychain] stringForKey:UDAuth0RefreshToken];
NSDate* idTokenExpirationDate = [[[FFJWT alloc] initWithToken:tokenString] expDate];
if (tokenString
// If the cached token expires within 10 min, tries refreshing a token.
&& [idTokenExpirationDate compare:[NSDate dateWithTimeIntervalSinceNow:AWSAuth0SignInProviderTokenRefreshBuffer]] == NSOrderedDescending) {
return [AWSTask taskWithResult:tokenString];
}
AWSTaskCompletionSource *taskCompletionSource = [AWSTaskCompletionSource taskCompletionSource];
A0Lock* lock = [A0Lock sharedLock];
A0APIClient* client = [lock apiClient];
A0AuthParameters* params = [A0AuthParameters newDefaultParams];
params[A0ParameterConnection] = [[FFCloudController sharedInstance] auth0ConnectionName:[[NSUserDefaults standardUserDefaults] integerForKey:UDLoginType]];
[client fetchNewIdTokenWithRefreshToken:refreshToken parameters:params success:^(A0Token * _Nonnull token)
{
NSLog(#"Success - token");
[[self keychain] setString:token.idToken ForKey:UDAuth0IdToken];
taskCompletionSource.result = token.idToken;
} failure:^(NSError * _Nonnull error)
{
NSLog(#"Error - token: %#", error);
taskCompletionSource.error = error;
}];
return taskCompletionSource.task;
}
- (BOOL)isLoggedIn {
NSData* profile = [[self keychain] dataForKey:UDAuth0Profile];
return [[NSUserDefaults standardUserDefaults] objectForKey:AWSAuth0SignInProviderKey] != nil && (profile != nil);
}
- (NSString *)userName {
return [[NSUserDefaults standardUserDefaults] objectForKey:AWSAuth0SignInProviderUserNameKey];
}
- (void)setUserName:(NSString *)userName {
[[NSUserDefaults standardUserDefaults] setObject:userName
forKey:AWSAuth0SignInProviderUserNameKey];
}
- (NSURL *)imageURL {
return [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:AWSAuth0SignInProviderImageURLKey]];
}
- (void)setImageURL:(NSURL *)imageURL {
[[NSUserDefaults standardUserDefaults] setObject:imageURL.absoluteString
forKey:AWSAuth0SignInProviderImageURLKey];
}
- (void)reloadSession {
if ([[NSUserDefaults standardUserDefaults] objectForKey:AWSAuth0SignInProviderKey]
&& [[self keychain] stringForKey:UDAuth0IdToken])
{
[self completeLogin];
}
}
- (void)completeLogin {
[[NSUserDefaults standardUserDefaults] setObject:#"YES"
forKey:AWSAuth0SignInProviderKey];
[[NSUserDefaults standardUserDefaults] synchronize];
[[AWSIdentityManager sharedInstance] completeLogin];
A0UserProfile *profile = [NSKeyedUnarchiver unarchiveObjectWithData:[[self keychain] dataForKey:UDAuth0Profile]];
self.userName = profile.email;
}
- (void)login
{
if ([[self keychain] stringForKey:UDAuth0IdToken])
{
[self completeLogin];
return;
}
A0AuthParameters* params = [A0AuthParameters newDefaultParams];
params[A0ParameterConnection] = [[FFCloudController sharedInstance] auth0ConnectionName:[[NSUserDefaults standardUserDefaults] integerForKey:UDLoginType]];
[[[A0Lock sharedLock] apiClient] loginWithUsername:[[FFKeyChain sharedInstance] stringForKey:UDEmail] password:[[FFKeyChain sharedInstance] stringForKey:UDPassword] parameters:params success:^(A0UserProfile * _Nonnull profile, A0Token * _Nonnull tokenInfo)
{
[[self keychain] setString:tokenInfo.idToken ForKey:UDAuth0IdToken];
[[self keychain] setString:tokenInfo.refreshToken ForKey:UDAuth0RefreshToken];
[[self keychain] setData:[NSKeyedArchiver archivedDataWithRootObject:profile] ForKey:UDAuth0Profile];
[self completeLogin];
} failure:^(NSError * _Nonnull error)
{
NSLog(#"Auth0 login error: %#", error);
}];
}
- (void)logout
{
[[NSUserDefaults standardUserDefaults] removeObjectForKey:AWSAuth0SignInProviderKey];
[[self keychain] removeObjectForKey:UDAuth0IdToken];
[[self keychain] removeObjectForKey:UDAuth0AccessToken];
[[self keychain] removeObjectForKey:UDAuth0RefreshToken];
[[self keychain] removeObjectForKey:UDAuth0Profile];
[[[A0Lock sharedLock] apiClient] logout];
}
#pragma mark - Application delegates
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
return YES;
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [[A0Lock sharedLock] handleURL:url sourceApplication:sourceApplication];
}
#end
It will only attempt to get an updated logins map if the credentials associated with the CredentialsProvider have expired. Have you tried calling clearCredentials on the CredentialsProvider when you log out to force it to refresh?

implement SLComposeViewController into Cocos2d

i can't seem to get the SLComposeViewController to come from a button on a cocos2D layer. If you could see anything that would stop this working please tell. Any help would be appreciated: N.B. viewController is a UIViewController
-(void)sceneSelect
{
NSString *message = [NSString stringWithFormat:#"Twitter Message"];
NSString *serviceType = [NSString stringWithFormat:#"SLServiceTypeTwitter"];
if ([SLComposeViewController isAvailableForServiceType:serviceType])
{
SLComposeViewController *tweetController = [SLComposeViewController composeViewControllerForServiceType:serviceType];
[tweetController setInitialText:message];
tweetController.completionHandler = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultDone){
//NSLog call
}
else if (result == SLComposeViewControllerResultCancelled){
//NSLog call
}
[viewController dismissViewControllerAnimated: YES completion: nil];
};
[[[CCDirector sharedDirector]openGLView]addSubview:viewController.view];
[viewController presentViewController:tweetController animated:YES completion:nil];
}
else
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Twitter" message:#"Twitter not working" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[alertView show];
}
}
Cocos2d 2.0 then use navigation controller in AppDelegate
AppController *app = (AppController*) [[UIApplication sharedApplication] delegate];
[[app navController] presentModalViewController:tweetController animated:YES];
HERE IS MY FULL TWITTER CODE: http://pastebin.com/hpRRJM1n

Shortening a URL containing & parameters

i have this URL and I am trying to shorten it through bit.ly API. Here is my code
NSString *url = #"http://www.example.com&username=abc&password=123&mode=offline";
NSString *requestStr = [NSString stringWithFormat:#"http://api.bit.ly/v3/shorten?login=%#&apiKey=%#&longUrl=%#&format=txt",login, api_key, url];
requestStr = [requestStr stringByReplacingOccurrencesOfString:#"&" withString:#"&"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:requestStr]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *response = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
I am getting a url in response which corresponds to only http://www.example.com
Surprisingly, &username=abc&password=123&mode=offline parts of the url are trimmed.
This happens only when I am doing it through xcode. On the website, it is working properly. PLease help.
NSString *url = #"https://www.googleapis.com/urlshortener/v1/url?key=UR_KEY";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"UR_LONG_URL",#"longUrl", nil];
[request setHTTPBody:[[dict JSONRepresentation] dataUsingEncoding:NSUTF8StringEncoding]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *response = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];

Is there a quick way to POST an NSDictionary to a Python/Django server?

I'm looking to send an NSDictionary up to a server running Django, and I would prefer if I had to do little or no work writing an encoder/parser.
Is there an easy way to accomplish this task?
iOS 5 has support for it in the framework. Look at NSJSONSerialization. Here is example code for post. Request object creation has been omitted in the code below.
NSDictionary *postDict = [NSDictionary dictionaryWithObjectsAndKeys:[NSDictionary dictionaryWithObjectsAndKeys:API_KEY, #"apiKey", userName, #"loginUserName", hashPassword, #"hashPassword", nil], #"loginReq", nil];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"content-type"];
NSError *error = nil;
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:postDict options:0 error:&error]];
iOS doesn't have support to do this as a one-liner, but you could do this:
#interface NSString (URLEncoding)
- (NSString *)urlEncodedUTF8String;
#end
#interface NSURLRequest (DictionaryPost)
+ (NSURLRequest *)postRequestWithURL:(NSURL *)url
parameters:(NSDictionary *)parameters;
#end
#implementation NSString (URLEncoding)
- (NSString *)urlEncodedUTF8String {
return (id)CFURLCreateStringByAddingPercentEscapes(0, (CFStringRef)self, 0,
(CFStringRef)#";/?:#&=$+{}<>,", kCFStringEncodingUTF8);
}
#end
#implementation NSURLRequest (DictionaryPost)
+ (NSURLRequest *)postRequestWithURL:(NSURL *)url
parameters:(NSDictionary *)parameters {
NSMutableString *body = [NSMutableString string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request addValue:#"application/x-www-form-urlencoded"
forHTTPHeaderField:#"Content-Type"];
for (NSString *key in parameters) {
NSString *val = [parameters objectForKey:key];
if ([body length])
[body appendString:#"&"];
[body appendFormat:#"%#=%#", [[key description] urlEncodedUTF8String],
[[val description] urlEncodedUTF8String]];
}
[request setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
return request;
}
#end
Then it's as simple as:
NSURL *url = [NSURL URLWithString:#"http://posttestserver.com/post.php"];
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInt:42], #"number",
#"apple", #"brand", nil];
NSURLRequest *request = [NSURLRequest postRequestWithURL:url parameters:params];
[NSURLConnection sendAsynchronousRequest:request queue:nil completionHandler:nil];
Please note that in this example we're not caring about the response. If you care about it, supply a block so you can do something with it.