facebook integration in iphone with Facebook sdk for ios5 and 6 - iphone

i have use FAcebook sdk 3.0 to integrate facebook.I have use sample code "HelloFacebookSample"
to post status.
I have change in Info.plist file with my AppId.
I have problem that show armv7s,armv7 architecture problem.I even solve out that by "Build Active Architecture Only "to YEs.
I have code that show button for login/logout for facebook
#import "HFViewController.h"
#import "AppDelegate.h"
#import <CoreLocation/CoreLocation.h>
#interface HFViewController () <FBLoginViewDelegate>
#property (strong, nonatomic) IBOutlet UIButton *buttonPostStatus;
#property (strong, nonatomic) id<FBGraphUser> loggedInUser;
- (IBAction)postStatusUpdateClick:(UIButton *)sender;
- (void)showAlert:(NSString *)message
result:(id)result
error:(NSError *)error;
#end
#implementation HFViewController
#synthesize shareStringFb;
#synthesize buttonPostStatus = _buttonPostStatus;
#synthesize loggedInUser = _loggedInUser;
- (void)viewDidLoad {
[super viewDidLoad];
// Create Login View so that the app will be granted "status_update" permission.
self.buttonPostStatus.enabled = YES;
FBLoginView *loginview = [[FBLoginView alloc] init];
loginview.frame = CGRectOffset(loginview.frame, 5, 5);
loginview.delegate = self;
[self.view addSubview:loginview];
[loginview sizeToFit];
statusText.text=self.shareStringFb;
{
// if the session is closed, then we open it here, and establish a handler for state changes
}
}
-(IBAction)backClick:(id)sender
{
[self.view removeFromSuperview];
}
- (void)viewDidUnload {
self.buttonPostStatus = nil;
self.loggedInUser = nil;
[super viewDidUnload];
}
- (void)loginViewShowingLoggedInUser:(FBLoginView *)loginView {
// first get the buttons set for login mode
self.buttonPostStatus.enabled = YES;
}
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
// here we use helper properties of FBGraphUser to dot-through to first_name and
// id properties of the json response from the server; alternatively we could use
// NSDictionary methods such as objectForKey to get values from the my json object
self.loggedInUser = user;
}
- (void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView {
self.buttonPostStatus.enabled = NO;
}
// Post Status Update button handler
- (IBAction)postStatusUpdateClick:(UIButton *)sender {
// Post a status update to the user's feed via the Graph API, and display an alert view
// with the results or an error.
NSString *message = [NSString stringWithFormat:#"Updating %#'s status at %#",
self.loggedInUser.first_name, [NSDate date]];
[FBRequestConnection startForPostStatusUpdate:self.shareStringFb
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:message result:result error:error];
self.buttonPostStatus.enabled = YES;
}];
self.buttonPostStatus.enabled = NO;
}
// Post Photo button handler
it show one button with login/logout in simulator but when i test in device it doesn't show that button.
Please any one can tell me what is problem?Why it not show that?Is there any other way to integrate Fb in ios 5 and 6 both.

Use for
this facebook sdk (3.1) for iOS6

ViewController.h
#import <FacebookSDK/FacebookSDK.h>
{
NSDictionary *dictionary;
NSString *user_email;
NSString *accessTokan;
NSMutableDictionary *fb_dict;
}
- (IBAction)btn_loginwithfacebook:(id)sender;
{
if (!FBSession.activeSession.isOpen)
{
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:nil 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_loginwithfacebook:sender];
}
}];
return;
}
[FBRequestConnection startWithGraphPath:#"me" parameters:[NSDictionary dictionaryWithObject:#"picture,id,birthday,email,name,gender,username" forKey:#"fields"] HTTPMethod:#"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (!error)
{
if ([result isKindOfClass:[NSDictionary class]])
{
//NSDictionary *dictionary;
if([result objectForKey:#"data"])
dictionary = (NSDictionary *)[(NSArray *)[result objectForKey:#"data"] objectAtIndex:0];
else
dictionary = (NSDictionary *)result;
//NSLog(#"dictionary : %#",dictionary);
user_email = [dictionary objectForKey:#"email"];
[dictionary retain];
//NSLog(#"%#",user_email);//
}
}
}];
accessTokan = [[[FBSession activeSession] accessTokenData] accessToken];
//NSLog(#"%#",accessTokan);
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=%#",accessTokan]]];
[request setHTTPMethod:#"GET"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
//NSLog(#"%#",str);
fb_dict = [str JSONValue];
[str release];}
FacebookAppID ::370546396320150
URL types
Item 0
URL Schemes
Item 0 ::fb370546396320150

Related

Calls to NSURLConnectionDataDelegate methods to download images only works occasionally

I currently have two UIImageViews in my storyboard, one of which downloads my own Facebook profile picture, and the other a friend's profile picture.
However, my issue is that only 60% of the time this works as expected, while the other 40% of the times my own profile picture appears where my friend's picture should show in the bottom, while the top box remains empty. I am unsure whether this is the result of how I call the NSURLConnectionDataDelegate methods as it downloads or completes view, or the nature of my requests called to Facebook.
I've pasted the condensed version of my two requests to Facebook in viewDidLoad, one which gets my own profile pic, and the other to get my friend's pic:
// ----- Gets my own profile picture, using requestForMe -----
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//handle response
if(!error){
//Some methods not included for breveity, includes facebookID used below
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
self.imageData = [[NSMutableData alloc] init];
switcher = 1;
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:pictureURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2.0f];
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if (!urlConnection){
NSLog(#"Failed to download picture");
}
}
}];
// ----- Gets a profile picture of my friend, using requestForMyFriends -----
FBRequest *requestForFriends = [FBRequest requestForMyFriends];
[requestForFriends startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error){
//Other methods not included, including facebookFriendID
NSURL *friendPictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookFriendID]];
self.supportImageData = [[NSMutableData alloc] init];
switcher = 2;
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:friendPictureURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:2.0f];
NSURLConnection *urlConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if (!urlConnection){
NSLog(#"Failed to download picture");
}
}
}];
Both requests make calls to the NSURLConnectionDataDelegate methods, and I use the switcher to decide when to load which picture:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// As chuncks of the image are received, we build our data file
if (switcher == 1) [self.imageData appendData:data];
if (switcher == 2)[self.supportImageData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//When the entire image is finished downloading
if (switcher == 1) {
UIImage *image = [UIImage imageWithData:self.imageData]; //puts the completed picture into the UI
self.titleImageView.image = image;
[self.titleImageView setClipsToBounds:YES];
}
if (switcher == 2) {
UIImage *supportImage = [UIImage imageWithData:self.supportImageData];
self.supportImageView.image = supportImage;
[self.titleImageView setClipsToBounds:YES];
}
}
You have two asynchronous processes, both of which can result in having your NSURLConnectionDataDelegate methods in self being called. But if they happen at the same time, they're going to step on top of each other (you're presumably using a single NSMutableData variable to reference the data being downloaded).
Either create dedicated class that you can instantiate once for each of your two NSURLConnection requests (a NSOperation based approach, like AFNetworking, is ideal), or use sendAsynchronousRequest instead. But don't use a single object as the delegate for two concurrent NSURLConnection requests at the same time.
If you wanted to see a minimalist download operation, it might look like:
// NetworkOperation.h
#import <Foundation/Foundation.h>
typedef void(^DownloadCompletion)(NSData *data, NSError *error);
#interface NetworkOperation : NSOperation
- (id)initWithURL:(NSURL *)url completion:(DownloadCompletion)completionBlock;
#property (nonatomic, copy) NSURL *url;
#property (nonatomic, copy) DownloadCompletion downloadCompletionBlock;
#end
and
// NetworkOperation.m
#import "NetworkOperation.h"
#interface NetworkOperation () <NSURLConnectionDataDelegate>
#property (nonatomic, readwrite, getter = isExecuting) BOOL executing;
#property (nonatomic, readwrite, getter = isFinished) BOOL finished;
#property (nonatomic, strong) NSMutableData *data;
#end
#implementation NetworkOperation
#synthesize finished = _finished;
#synthesize executing = _executing;
- (id)initWithURL:(NSURL *)url completion:(DownloadCompletion)downloadCompletionBlock
{
self = [super init];
if (self) {
self.url = url;
self.downloadCompletionBlock = downloadCompletionBlock;
_executing = NO;
_finished = NO;
}
return self;
}
#pragma mark - NSOperation related stuff
- (void)start
{
if ([self isCancelled]) {
self.finished = YES;
return;
}
self.executing = YES;
NSURLRequest *request = [NSURLRequest requestWithURL:self.url];
NSAssert(request, #"%s: requestWithURL failed for URL '%#'", __FUNCTION__, [self.url absoluteString]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
}
- (void)setExecuting:(BOOL)executing
{
[self willChangeValueForKey:#"isExecuting"];
_executing = executing;
[self didChangeValueForKey:#"isExecuting"];
}
- (void)setFinished:(BOOL)finished
{
[self willChangeValueForKey:#"isFinished"];
_finished = finished;
[self didChangeValueForKey:#"isFinished"];
}
- (BOOL)isConcurrent
{
return YES;
}
#pragma mark NSURLConnectionDataDelegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.data = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if ([self isCancelled]) {
[connection cancel];
self.executing = NO;
self.finished = YES;
return;
}
[self.data appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (self.downloadCompletionBlock) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.downloadCompletionBlock(self.data, nil);
self.downloadCompletionBlock = nil;
}];
}
self.executing = NO;
self.finished = YES;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
if (self.downloadCompletionBlock) {
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
self.downloadCompletionBlock(nil, error);
self.downloadCompletionBlock = nil;
}];
}
self.executing = NO;
self.finished = YES;
}
#end
And then, when you wanted to use it, it might look like:
NSOperationQueue *networkQueue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 4;
// ----- Gets my own profile picture, using requestForMe -----
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
//handle response
if(!error) {
//Some methods not included for breveity, includes facebookID used below
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
[networkQueue addOperation:[[NetworkOperation alloc] requestWithURL:pictureURL completion:^(NSData *data, NSError *error) {
if (!error) {
self.meImageView.image = [UIImage imageWithData:data];
}
}]];
}
}];
// ----- Gets a profile picture of my friend, using requestForMyFriends -----
FBRequest *requestForFriends = [FBRequest requestForMyFriends];
[requestForFriends startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error){
//Other methods not included, including facebookFriendID
NSURL *friendPictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookFriendID]];
[networkQueue addOperation:[[NetworkOperation alloc] requestWithURL:friendPictureURL completion:^(NSData *data, NSError *error) {
if (!error) {
self.friendImageView.image = [UIImage imageWithData:data];
}
}]];
}
}];

Post to Facebook not working from delegate

I have added FBSdk in my project along with SBJson classes, what files should i import in my second view controller to work my code ?
I want to post on Fb using the description under url so for that i need to include this code into my second view controller, but i am stuck in a part i founded that the below code should be added in the second view controller but the "delegate:self" not works, as i am doing this first time so can any one guide me how should i code in my second view controller keeping into account the values from the app delegate (How should i get the values from the app delegate of FB to the second view so that i can add this code in second code plz can any one correct this code)
facebook = [[Facebook alloc] initWithAppId:#"YOUR_APP_ID"];
// how should i take this id from the app delegate ?
NSArray* permissions = [NSArray arrayWithObjects:#"read_stream",
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
NSMutableDictionary* params = [[NSMutableDictionary alloc]
initWithCapacity:1]
[params setObject:#"Testing" forKey:#"name"];
[params setObject:#"IMAGE_URL" forKey:#"picture"];
[params setObject:#"Description" forKey:#"description"];
[facebook requestWithGraphPath:#"me/feed"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
Is the above code correct ?
How should i implement it in my second view controller in -(void)fb_share (method).
My App Delegate File is Like this :
#import "AppDelegate.h"
#import "ViewController.h"
#import "ServerRequests.h"
#import "DBManager.h"
#import "SBJson.h"
#include "FBSession.h"
#import "FBRequest.h"
#import "FBGraphUser.h"
NSString *const FBSessionStateChangedNotification = #"com.myapp:FBSessionStateChangedNotification";
#implementation AppDelegate
#synthesize userId;
#synthesize dbSnyced;
#synthesize fbId;
#synthesize loginView;
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ self.fbId = #"-1";
self.dbSnyced = NO;
self.loginView = nil;
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
self.viewController = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
self.navigationController = [[[UINavigationController alloc] initWithRootViewController:self.viewController] autorelease];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
if (![self openSessionWithAllowLoginUI:NO]) {
[self showLogin:NO];
}
return YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[self checkAccountLogin];
}
- (void) applicationDidEnterBackground:(UIApplication *)application
{
[self hideLogin:NO];
}
- (void) applicationWillTerminate:(UIApplication *)application
{
NSLog(#"applicationWillTerminate");
[self hideLogin:NO];
[FBSession.activeSession close];
}
- (void) checkAccountLogin
{
self.dbSnyced = NO;
if([ServerRequests serverIsReachableAlertIfNo:YES]) {
DBManager *db = [[[DBManager alloc] initWithPath:DB_NAME] autorelease];
NSDictionary *userDic = [[db smartQueryForArrayWithStatement:#"SELECT * FROM table WHERE id=1"] objectAtIndex:0];
NSString *loginType = [userDic objectForKey:#"login_type"];
if([loginType isEqualToString:#"none"]) {
NSLog(#"no login type");
[self showLogin:NO];
}
else {
self.userId = [[userDic objectForKey:#"user_id"] intValue];
if([loginType isEqualToString:#"Facebook"]) {
NSLog(#"Facebook account");
[FBSession.activeSession handleDidBecomeActive];
}
else if([loginType isEqualToString:#"MyApp"]) {
NSLog(#"MyApp account");
}
}
}
}
#pragma - Fb stuff
/*
* Callback for session changes.
*/
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
{
NSLog(#"sessionStateChanged");
switch (state) {
case FBSessionStateOpen:
if (!error) {
[self handleFbUserDetails];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName:FBSessionStateChangedNotification object:session];
if (error) {
NSLog(#"error: %#", error.localizedDescription);
if(self.loginView) {
[self.loginView hideLoading];
}
}
}
/*
* Opens a Facebook session and optionally shows the login UX.
*/
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
return [FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
/*
* If we have a valid session at the time of openURL call, we handle
* Facebook transitions by passing the url argument to handleOpenURL
*/
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
// attempt to extract a token from the url
return [FBSession.activeSession handleOpenURL:url];
}
- (BOOL) activeFBSession
{
return FBSession.activeSession.isOpen;
}
- (void) closeFBSession
{
NSLog(#"closeFBSession");
[FBSession.activeSession closeAndClearTokenInformation];
}
- (void) showLogin:(BOOL)animated
{
if(!self.loginView) {
self.loginView = [[[LoginViewController alloc] init] autorelease];
[[self.navigationController topViewController] presentViewController:self.loginView animated:animated completion:nil];
}
}
- (void) hideLogin:(BOOL)animated
{
if(self.loginView) {
[self.viewController gotToTab:0];
[self.loginView hideLoading];
[[self.navigationController topViewController] dismissViewControllerAnimated:animated completion:^{
self.loginView = nil;
NSLog(#"self.loginView = nil");
}];
}
}
- (void) handleFbUserDetails
{
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
NSLog(#"fb connected");
self.fbId = [user objectForKey:#"id"];
self.userId = -1;
ASIFormDataRequest *request = [ServerRequests ASIFormDataRequestForSrcipt:#"facebookUser"];
[request setPostValue:[user objectForKey:#"id"] forKey:#"fbId"];
[request setPostValue:user.first_name forKey:#"first_name"];
[request setPostValue:user.last_name forKey:#"last_name"];
[request setPostValue:user.location.name forKey:#"location"];
[request setCompletionBlock:^{
NSString *response = [request responseString];
NSLog(#"facebookUser response: %#", response);
if([response rangeOfString:#"ERROR"].location == NSNotFound) {
self.userId = [response intValue];
DBManager *db = [[DBManager alloc] initWithPath:DB_NAME];
NSString *q = [NSString stringWithFormat:#"UPDATE table SET login_type = 'Facebook', user_id = '%#' WHERE id = 1", response];
NSLog(#"%#", q);
[db executeStatement:q];
[db release];
}
else {
}
[self sessionBecameActive];
}];
[request startAsynchronous];
[self hideLogin:YES];
}
else {
NSLog(#"error: %#", error.localizedDescription);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Facebook Request Error" message:#"Cannot connect to Facebook." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
alert.delegate = self;
[alert show];
[alert release];
if(self.loginView) {
[self.loginView hideLoading];
}
}
[ServerRequests SyncDataBase];
}];
}
- (void) signOut
{
[self closeFBSession];
DBManager *db = [[DBManager alloc] initWithPath:DB_NAME];
[db executeStatement:#"UPDATE table SET login_type = 'none' WHERE id = 1"];
[db release];
[self showLogin:YES];
}
- (void) sessionBecameActive
{
[self.viewController sessionBecameActive];
}
#end
Can any one figure out what code should i write in the -(void)fb_share method in second view controller by getting values from the delegate ?
Any Help !
I did this ... and getting Error: HTTP status code: 400 ... but the user name get's displayed on alert
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
// NSArray* permissions = [NSArray arrayWithObjects:#"read_stream",
// #"publish_stream", nil];
// [facebook authorize:permissions delegate:self];
self.params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
#"https://developers.facebook.com/ios", #"link",
#"https://developers.facebook.com/attachment/iossdk_logo.png", #"picture",
#"Facebook SDK for iOS", #"name",
#"Build great social apps and get more installs.", #"caption",
#"The Facebook SDK for iOS makes it easier and faster to develop Facebook integrated iOS apps.", #"description",
nil];
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Upload to FB?"
message:[NSString stringWithFormat:#"Upload to ""%#"" Account?", user.name]
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"No",#"Yes", nil];
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:self.params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Success"
message:#"PostUploaded"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[tmp show];
[tmp release];
}
}];
[tmp show];
[tmp release];
}
}];
.. what should i do now ?
declare facebook as a property in .h file of your appDelegate
then in second view controller import AppDelegate
in .m file where you want the Facebook object
get it like
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
Facebook *facebook = appDelegate.facebook;

Advertisements not removed after IAP unless app is restarted?

In my app, there is code that, if a button is pressed the user can upgrade the app and remove the advertisements, it calls the MKStoreKit and once the user purchases the upgrade, the adverts do remain in the app UNTIL the app is restarted.
I want to fix this, so the advertisements are removed immediately, but how would I go about doing this?
Here is some of the code;
-(IBAction)removeAds:(id)sender
{
if (![MKStoreManager isFeaturePurchased:#"com.davidsapps.puzzler.removeads"]) { //
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Upgrade App" message:#"To upgrade and remove all advertisements from this app Please click OK to purchase the upgrade!" delegate:self cancelButtonTitle:#"No Thanks" otherButtonTitles:#"Yes Please",nil];
[alert show];
[alert release];
}
}
The alert it links to;
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0){
//cancel button clicked. Do something here or nothing here
}
else{
//other button indexes clicked
[[MKStoreManager sharedManager] buyFeature:#- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 0){
//cancel button clicked. Do something here or nothing here
}
else{
//other button indexes clicked
[[MKStoreManager sharedManager] buyFeature:#"com.idevver.mybatterypal.upgrade"];
}
}
}
Using MKStoreKit
Is there anything I can do to make it remove the advertisements without the user having to restart the app?
Thanks,
Chris
EDIT - the advertisements are Admob Mediation, using this code in the ViewDidLoad
- (void)viewDidLoad {
bannerView_ = [[GADBannerView alloc] initWithAdSize:kGADAdSizeSmartBannerPortrait];
bannerView_.adUnitID = MY_BANNER_UNIT_ID;
CGRect screenRect = [[UIScreen mainScreen] bounds];
CGFloat screenWidth = screenRect.size.width;
CGFloat screenHeight = screenRect.size.height;
CGFloat screenXPos = (screenWidth /2);
CGFloat screenYPos = screenHeight - 90;
[bannerView_ setCenter:CGPointMake(screenXPos, screenYPos)];
bannerView_.rootViewController = self;
bannerView_.adUnitID = MY_BANNER_UNIT_ID;
bannerView_.rootViewController = self;
[self.view addSubview:bannerView_];
This is the code that actually calls the advertisement banner, it is in an if/else statement later in the viewDidLoad
if (![MKStoreManager isFeaturePurchased:#"com.davidsapps.puzzler.removeads"]) { //
[bannerView_ loadRequest:[GADRequest request]];
}
So I guess somehow when the feature is purchased, I need to add to the MKStoreManager.m file something to say dismiss the bannerView_ code above?
Would that work?
EDIT 2 - Full .m file for the in-app code (with thanks to MugunthKumar for a wonderful kit)
//
// MKStoreManager.m
// MKStoreKit
//
// Created by Mugunth Kumar on 17-Nov-2010.
// Copyright 2010 Steinlogic. All rights reserved.
// File created using Singleton XCode Template by Mugunth Kumar (http://mugunthkumar.com
// Permission granted to do anything, commercial/non-commercial with this file apart from removing the line/URL above
// Read my blog post at http://mk.sg/1m on how to use this code
// As a side note on using this code, you might consider giving some credit to me by
// 1) linking my website from your app's website
// 2) or crediting me inside the app's credits page
// 3) or a tweet mentioning #mugunthkumar
// 4) A paypal donation to mugunth.kumar#gmail.com
//
// A note on redistribution
// While I'm ok with modifications to this source code,
// if you are re-publishing after editing, please retain the above copyright notices
#import "MKStoreManager.h"
#import "GADBannerView.h"
#import "AppDelegate.h"
#interface MKStoreManager (PrivateMethods)
- (void) requestProductData;
- (BOOL) canCurrentDeviceUseFeature: (NSString*) featureID;
- (BOOL) verifyReceipt:(NSData*) receiptData;
- (void) enableContentForThisSession: (NSString*) productIdentifier;
#end
#implementation MKStoreManager
#synthesize purchasableObjects = _purchasableObjects;
#synthesize storeObserver = _storeObserver;
static NSString *ownServer = nil;
static __weak id<MKStoreKitDelegate> _delegate;
static MKStoreManager* _sharedStoreManager;
- (void)dealloc {
[_purchasableObjects release];
[_storeObserver release];
[_sharedStoreManager release];
[super dealloc];
}
#pragma mark Delegates
+ (id)delegate {
return _delegate;
}
+ (void)setDelegate:(id)newDelegate {
_delegate = newDelegate;
}
#pragma mark Singleton Methods
+ (MKStoreManager*)sharedManager
{
#synchronized(self) {
if (_sharedStoreManager == nil) {
#if TARGET_IPHONE_SIMULATOR
NSLog(#"You are running in Simulator MKStoreKit runs only on devices");
#else
_sharedStoreManager = [[self alloc] init];
_sharedStoreManager.purchasableObjects = [[NSMutableArray alloc] init];
[_sharedStoreManager requestProductData];
_sharedStoreManager.storeObserver = [[MKStoreObserver alloc] init];
[[SKPaymentQueue defaultQueue] addTransactionObserver:_sharedStoreManager.storeObserver];
#endif
}
}
return _sharedStoreManager;
}
+ (id)allocWithZone:(NSZone *)zone
{
#synchronized(self) {
if (_sharedStoreManager == nil) {
_sharedStoreManager = [super allocWithZone:zone];
return _sharedStoreManager; // assignment and return on first allocation
}
}
return nil; //on subsequent allocation attempts return nil
}
- (id)copyWithZone:(NSZone *)zone
{
return self;
}
- (id)retain
{
return self;
}
- (unsigned)retainCount
{
return UINT_MAX; //denotes an object that cannot be released
}
- (void)release
{
//do nothing
}
- (id)autorelease
{
return self;
}
#pragma mark Internal MKStoreKit functions
- (void) restorePreviousTransactions
{
[[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
}
-(void) requestProductData
{
SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:[NSSet setWithObjects:
kFeatureAId,
kConsumableFeatureBId,
kConsumableBaseFeatureId,
nil]];
request.delegate = self;
[request start];
}
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
[self.purchasableObjects addObjectsFromArray:response.products];
#ifndef NDEBUG
for(int i=0;i<[self.purchasableObjects count];i++)
{
SKProduct *product = [self.purchasableObjects objectAtIndex:i];
NSLog(#"Feature: %#, Cost: %f, ID: %#",[product localizedTitle],
[[product price] doubleValue], [product productIdentifier]);
}
for(NSString *invalidProduct in response.invalidProductIdentifiers)
NSLog(#"Problem in iTunes connect configuration for product: %#", invalidProduct);
#endif
[request autorelease];
isProductsAvailable = YES;
if([_delegate respondsToSelector:#selector(productFetchComplete)])
[_delegate productFetchComplete];
}
// call this function to check if the user has already purchased your feature
+ (BOOL) isFeaturePurchased:(NSString*) featureId
{
return [[NSUserDefaults standardUserDefaults] boolForKey:featureId];
}
// Call this function to populate your UI
// this function automatically formats the currency based on the user's locale
- (NSMutableArray*) purchasableObjectsDescription
{
NSMutableArray *productDescriptions = [[NSMutableArray alloc] initWithCapacity:[self.purchasableObjects count]];
for(int i=0;i<[self.purchasableObjects count];i++)
{
SKProduct *product = [self.purchasableObjects objectAtIndex:i];
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
[numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
[numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
[numberFormatter setLocale:product.priceLocale];
NSString *formattedString = [numberFormatter stringFromNumber:product.price];
[numberFormatter release];
// you might probably need to change this line to suit your UI needs
NSString *description = [NSString stringWithFormat:#"%# (%#)",[product localizedTitle], formattedString];
#ifndef NDEBUG
NSLog(#"Product %d - %#", i, description);
#endif
[productDescriptions addObject: description];
}
[productDescriptions autorelease];
return productDescriptions;
}
- (void) buyFeature:(NSString*) featureId
{
if([self canCurrentDeviceUseFeature: featureId])
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Review request approved", #"")
message:NSLocalizedString(#"You can use this feature for reviewing the app.", #"")
delegate:self
cancelButtonTitle:NSLocalizedString(#"Dismiss", #"")
otherButtonTitles:nil];
[alert show];
[alert release];
[self enableContentForThisSession:featureId];
return;
}
if ([SKPaymentQueue canMakePayments])
{
SKPayment *payment = [SKPayment paymentWithProductIdentifier:featureId];
[[SKPaymentQueue defaultQueue] addPayment:payment];
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"In-App Purchasing disabled", #"")
message:NSLocalizedString(#"Check your parental control settings and try again later", #"")
delegate:self
cancelButtonTitle:NSLocalizedString(#"Dismiss", #"")
otherButtonTitles: nil];
[alert show];
[alert release];
}
}
- (BOOL) canConsumeProduct:(NSString*) productIdentifier
{
int count = [[NSUserDefaults standardUserDefaults] integerForKey:productIdentifier];
return (count > 0);
}
- (BOOL) canConsumeProduct:(NSString*) productIdentifier quantity:(int) quantity
{
int count = [[NSUserDefaults standardUserDefaults] integerForKey:productIdentifier];
return (count >= quantity);
}
- (BOOL) consumeProduct:(NSString*) productIdentifier quantity:(int) quantity
{
int count = [[NSUserDefaults standardUserDefaults] integerForKey:productIdentifier];
if(count < quantity)
{
return NO;
}
else
{
count -= quantity;
[[NSUserDefaults standardUserDefaults] setInteger:count forKey:productIdentifier];
return YES;
}
}
-(void) enableContentForThisSession: (NSString*) productIdentifier
{
if([_delegate respondsToSelector:#selector(productPurchased:)])
[_delegate productPurchased:productIdentifier];
}
#pragma mark In-App purchases callbacks
// In most cases you don't have to touch these methods
-(void) provideContent: (NSString*) productIdentifier
forReceipt:(NSData*) receiptData
{
if(ownServer != nil && SERVER_PRODUCT_MODEL)
{
// ping server and get response before serializing the product
// this is a blocking call to post receipt data to your server
// it should normally take a couple of seconds on a good 3G connection
if(![self verifyReceipt:receiptData]) return;
}
NSRange range = [productIdentifier rangeOfString:kConsumableBaseFeatureId];
NSString *countText = [productIdentifier substringFromIndex:range.location+[kConsumableBaseFeatureId length]];
int quantityPurchased = [countText intValue];
if(quantityPurchased != 0)
{
int oldCount = [[NSUserDefaults standardUserDefaults] integerForKey:productIdentifier];
oldCount += quantityPurchased;
[[NSUserDefaults standardUserDefaults] setInteger:oldCount forKey:productIdentifier];
}
else
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:productIdentifier];
}
[[NSUserDefaults standardUserDefaults] synchronize];
if([_delegate respondsToSelector:#selector(productPurchased:)])
[_delegate productPurchased:productIdentifier];
UIAlertView* alert = [[UIAlertView alloc] initWithTitle:#"In-App Upgrade" message:#"Successfull removal of advertisements upgrade - thankyou" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
- (void) transactionCanceled: (SKPaymentTransaction *)transaction
{
#ifndef NDEBUG
NSLog(#"User cancelled transaction: %#", [transaction description]);
#endif
if([_delegate respondsToSelector:#selector(transactionCanceled)])
[_delegate transactionCanceled];
}
- (void) failedTransaction: (SKPaymentTransaction *)transaction
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[transaction.error localizedFailureReason]
message:[transaction.error localizedRecoverySuggestion]
delegate:self
cancelButtonTitle:NSLocalizedString(#"Dismiss", #"")
otherButtonTitles: nil];
[alert show];
[alert release];
}
#pragma mark In-App purchases promo codes support
// This function is only used if you want to enable in-app purchases for free for reviewers
// Read my blog post http://mk.sg/31
- (BOOL) canCurrentDeviceUseFeature: (NSString*) featureID
{
NSString *uniqueID = [[UIDevice currentDevice] uniqueIdentifier];
// check udid and featureid with developer's server
if(ownServer == nil) return NO; // sanity check
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", ownServer, #"featureCheck.php"]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *postData = [NSString stringWithFormat:#"productid=%#&udid=%#", featureID, uniqueID];
NSString *length = [NSString stringWithFormat:#"%d", [postData length]];
[theRequest setValue:length forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[[NSError alloc] init] autorelease];
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest
returningResponse:&urlResponse
error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
BOOL retVal = NO;
if([responseString isEqualToString:#"YES"])
{
retVal = YES;
}
[responseString release];
return retVal;
}
// This function is only used if you want to enable in-app purchases for free for reviewers
// Read my blog post http://mk.sg/
-(BOOL) verifyReceipt:(NSData*) receiptData
{
if(ownServer == nil) return NO; // sanity check
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", ownServer, #"verifyProduct.php"]];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:60];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
NSString *receiptDataString = [[NSString alloc] initWithData:receiptData encoding:NSASCIIStringEncoding];
NSString *postData = [NSString stringWithFormat:#"receiptdata=%#", receiptDataString];
[receiptDataString release];
NSString *length = [NSString stringWithFormat:#"%d", [postData length]];
[theRequest setValue:length forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:[postData dataUsingEncoding:NSASCIIStringEncoding]];
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[[NSError alloc] init] autorelease];
NSData *responseData = [NSURLConnection sendSynchronousRequest:theRequest
returningResponse:&urlResponse
error:&error];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding];
BOOL retVal = NO;
if([responseString isEqualToString:#"YES"])
{
retVal = YES;
}
[responseString release];
return retVal;
}
#end
When the purchase completes, it is up to you to remove the ads. Do something similar to this.
[bannerView removeFromSuperview];
All you have to do is hide the ads when the purchase completes.

SLRequest performRequestWithHandler does not work in ios 6

I am trying to build simple prototype where I post some text to my facebook account. I have read the ios 6 facebook integration documentation and came up with following code. Everything seems to work fine until I hit the last block where I create SLRequest object in method postTextToFacebook and try to execute performRequestWithHandler with handler block. Control never does inside the handler block. I am assuming that performRequestWithHandler call is not successful in this case. Any one have done with successfully? Here is code for your reference.
#import <Social/Social.h>
#import "ViewController.h"
#implementation ViewController
#synthesize facebookAccount;
#synthesize accountStore;
#synthesize textToPost;
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(IBAction) postToFacebook:(id)sender
{
self.statusLabel.text = #"Logging in ...";
if(self.accountStore == nil)
{
self.accountStore = [[ACAccountStore alloc] init];
}
ACAccountType *facebookAccountType = [self.accountStore enter code hereaccountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSMutableDictionary *myOptions = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"172197712918906", ACFacebookAppIdKey,
[NSArray arrayWithObjects:#"email", #"user_about_me", #"user_likes", nil], ACFacebookPermissionsKey, ACFacebookAudienceFriends, ACFacebookAudienceKey, nil];
[self.accountStore requestAccessToAccountsWithType:facebookAccountType options:myOptions completion:^(BOOL granted, NSError *error){
__block NSString *statusText;
if(granted)
{
NSArray *accounts = [self.accountStore accountsWithAccountType:facebookAccountType];
self.facebookAccount = [accounts lastObject];
[myOptions setObject:[NSArray arrayWithObjects:#"publish_stream", nil] forKey:ACFacebookPermissionsKey];
[self.accountStore requestAccessToAccountsWithType:facebookAccountType options:myOptions completion:^(BOOL granted, NSError *error) {
__block NSString *statusText1;
if(granted && error == nil)
{
NSArray *accounts = [self.accountStore accountsWithAccountType:facebookAccountType];
self.facebookAccount = [accounts lastObject];
[self postTextToFacebook];
statusText1 = #"Text Posted.";
}
else{
statusText1 = #"Publish Failed.";
}
dispatch_async(dispatch_get_main_queue(), ^{
self.statusLabel.text = statusText1;
});
}];
}
else{
statusText = #"Login Failed.";
NSLog(#"Error = %#",error);
}
}];
}
-(void) postTextToFacebook
{
NSDictionary *parameters = #{#"message":self.textToPost.text};
NSURL *feedURL = [NSURL URLWithString:#"https://graphs.facebook.com/me/feed"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodPOST URL:feedURL parameters:parameters];
request.account = self.facebookAccount;
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSLog(#"Facebook request received, status code %d", urlResponse.statusCode);
NSString *response = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response data: %#", response);
//handle errors
if(error == nil)
{
dispatch_async(dispatch_get_main_queue(), ^{
self.statusLabel.text = #"text posted to facebook";
});
}
}];
}
#end
Your url should be
https://graph.facebook.com/me/feed
instead of
https://graphs.facebook.com/me/feed
I was having a same issue and got an NSURLErrorDomain -1003 error on it.

Facebook sdk post on wall on iPhone app

I have a problem with implementing Facebook posting on wall in my iPhone application.
I installed SDK and linked framework
login is working fine. here's the code:
-(IBAction)loginButtonPressed:(id)sender
{
NSLog(#"loginButtonPressed: called");
AppDelegate *appdel=[[UIApplication sharedApplication] delegate];
appdel.facebookSession=[[FBSession alloc] init];
[appdel.facebookSession openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error)
{
//
}];
}
But I have a problem with posting message on user's wall. Here's the code:
-(IBAction)likeButtonPressed:(id)sender
{
NSLog(#"likeButtonPressed: called");
// Post a status update to the user's feedm via the Graph API, and display an alert view
// with the results or an error.
NSString *message = #"test message";
NSDictionary *params = [NSDictionary dictionaryWithObject:message forKey:#"message"];
// use the "startWith" helper static on FBRequest to both create and start a request, with
// a specified completion handler.
[FBRequest startWithGraphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:message result:result error:error];
}];
}
Help me please. What's wrong with my code? Or should I add some permissions to login request?
this code worked for me.
First we must
#import <FBiOSSDK/FacebookSDK.h>
then
#property (strong, nonatomic) FBRequestConnection *requestConnection;
and of course do not forget to synthesize:
#synthesize requestConnection;
the code itself:
-(IBAction)likeButtonPressed:(id)sender
{
NSLog(#"likeButtonPressed: called");
// FBSample logic
// Check to see whether we have already opened a session.
if (FBSession.activeSession.isOpen)
{
// login is integrated with the send button -- so if open, we send
[self postOnWall];
}
else
{
[FBSession sessionOpenWithPermissions:[NSArray arrayWithObjects:#"publish_stream", nil]
completionHandler:
^(FBSession *session,
FBSessionState status,
NSError *error)
{
// if login fails for any reason, we alert
if (error)
{
NSLog(#" login failed");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
// if otherwise we check to see if the session is open, an alternative to
// to the FB_ISSESSIONOPENWITHSTATE helper-macro would be to check the isOpen
// property of the session object; the macros are useful, however, for more
// detailed state checking for FBSession objects
}
else if (FB_ISSESSIONOPENWITHSTATE(status))
{
NSLog(#" sending post on wall request...");
// send our requests if we successfully logged in
[self postOnWall];
}
}];
};
}
- (void)postOnWall
{
NSNumber *testMessageIndex=[[NSNumber alloc] init];
if ([[NSUserDefaults standardUserDefaults] objectForKey:#"testMessageIndex"]==nil)
{
testMessageIndex=[NSNumber numberWithInt:100];
}
else
{
testMessageIndex=[[NSUserDefaults standardUserDefaults] objectForKey:#"testMessageIndex"];
};
testMessageIndex=[NSNumber numberWithInt:[testMessageIndex intValue]+1];
[[NSUserDefaults standardUserDefaults] setObject:testMessageIndex forKey:#"testMessageIndex"];
[[NSUserDefaults standardUserDefaults] synchronize];
// create the connection object
FBRequestConnection *newConnection = [[FBRequestConnection alloc] init];
// create a handler block to handle the results of the request for fbid's profile
FBRequestHandler handler =
^(FBRequestConnection *connection, id result, NSError *error) {
// output the results of the request
[self requestCompleted:connection forFbID:#"me" result:result error:error];
};
// create the request object, using the fbid as the graph path
// as an alternative the request* static methods of the FBRequest class could
// be used to fetch common requests, such as /me and /me/friends
NSString *messageString=[NSString stringWithFormat:#"wk test message %i", [testMessageIndex intValue]];
FBRequest *request=[[FBRequest alloc] initWithSession:FBSession.activeSession graphPath:#"me/feed" parameters:[NSDictionary dictionaryWithObject:messageString forKey:#"message"] HTTPMethod:#"POST"];
// add the request to the connection object, if more than one request is added
// the connection object will compose the requests as a batch request; whether or
// not the request is a batch or a singleton, the handler behavior is the same,
// allowing the application to be dynamic in regards to whether a single or multiple
// requests are occuring
[newConnection addRequest:request completionHandler:handler];
// if there's an outstanding connection, just cancel
[self.requestConnection cancel];
// keep track of our connection, and start it
self.requestConnection = newConnection;
[newConnection start];
}
// FBSample logic
// Report any results. Invoked once for each request we make.
- (void)requestCompleted:(FBRequestConnection *)connection
forFbID:fbID
result:(id)result
error:(NSError *)error
{
NSLog(#"request completed");
// not the completion we were looking for...
if (self.requestConnection &&
connection != self.requestConnection)
{
NSLog(#" not the completion we are looking for");
return;
}
// clean this up, for posterity
self.requestConnection = nil;
if (error)
{
NSLog(#" error");
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
// error contains details about why the request failed
[alert show];
}
else
{
NSLog(#" ok");
};
}
try this code
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* facebookCookies = [cookies cookiesForURL:
[NSURL URLWithString:#"http://login.facebook.com"]];
for (NSHTTPCookie* cookie in facebookCookies) {
[cookies deleteCookie:cookie];
}
NSString *FBBody = [NSString stringWithFormat:#"your message you want to post"];
UIImage *img=[UIImage imageNamed:[NSString stringWithFormat:image naemif you want to post]];
FBFeedPost *post = [[FBFeedPost alloc] initWithPhoto:img name:FBBody];
[post publishPostWithDelegate:self];
[[UIAppDelegate indicator] startAnimating];
IFNNotificationDisplay *display = [[IFNNotificationDisplay alloc] init];
display.type = NotificationDisplayTypeLoading;
display.tag = NOTIFICATION_DISPLAY_TAG;
you should set Permissions:"status_update".
like this :
FBLoginView *loginview = [[FBLoginView alloc] initWithPermissions:[NSArray arrayWithObject:#"status_update"]];
or
FBSession *fbSession = [[FBSession alloc] initWithPermissions:[NSArray arrayWithObject:#"status_update"]];