The header:
#import <UIKit/UIKit.h>
#import <FacebookSDK/FacebookSDK.h>
#interface ViewController : UIViewController<UITextFieldDelegate>
{
IBOutlet UITextField *update;
NSString *status;
}
#property (nonatomic, copy) IBOutlet NSString *status;
#end
.m File:
#import "ViewController.h"
#interface ViewController ()
#property (strong, nonatomic) IBOutlet UIButton *buttonPostStatus;
#property (strong, nonatomic) id<FBGraphUser> loggedInUser;
#property (strong, nonatomic) IBOutlet UILabel *labelFirstName;
#property (strong,nonatomic) IBOutlet UITextField *update;
#property (strong,nonatomic) IBOutlet UILabel *dob;
#property (strong,nonatomic) IBOutlet UILabel *profilename;
- (IBAction)postStatusUpdateClick:(UIButton *)sender;
#end
#implementation ViewController
#synthesize buttonPostStatus = _buttonPostStatus;
#synthesize loggedInUser = _loggedInUser;
#synthesize labelFirstName = _labelFirstName;
#synthesize update;
#synthesize dob;
#synthesize profilename;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
FBLoginView *loginview = [[FBLoginView alloc] init];
loginview.frame = CGRectOffset(loginview.frame, 5, 5);
if ([self respondsToSelector:#selector(setEdgesForExtendedLayout:)]) {
loginview.frame = CGRectOffset(loginview.frame, 5, 25);
}
loginview.delegate = self;
self.labelFirstName = nil;
self.loggedInUser = nil;
[self.view addSubview:loginview];
[loginview sizeToFit];
NSString *status = update.text;
}
- (void)viewDidUnload {
self.buttonPostStatus = nil;
[super viewDidUnload];
}
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
self.labelFirstName.text = [NSString stringWithFormat:#"Hello %# %#", user.first_name, user.last_name ];
self.loggedInUser = user;
self.dob.text= [NSString stringWithFormat:#"Birthday- %#", user.birthday];
NSLog(user.birthday);
NSLog(self.labelFirstName.text);
//NSLog(user.dob);
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)loginView:(FBLoginView *)loginView handleError:(NSError *)error {
NSLog(#"FBLoginView encountered an error=%#", error);
}
- (void) performPublishAction:(void (^)(void)) action {
// we defer request for permission to post to the moment of post, then we check for the permission
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
// if we don't already have the permission, then we request it now
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
} else if (error.fberrorCategory != FBErrorCategoryUserCancelled){
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Permission denied"
message:#"Unable to get permission to post"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}];
} else {
action();
}
}
- (IBAction)postStatusUpdateClick:(UIButton *)sender {
NSURL *urlToShare = [NSURL URLWithString:#"htts.facebook.com/ios"];
FBAppCall *appCall = [FBDialogs presentShareDialogWithLink:urlToShare
name:#"Hello Facebook"
caption:nil
description:#"The 'Hello Facebook' sample application showcases simple Facebook integration."
picture:nil
clientState:nil
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if (error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success!");
}
}];
[self performPublishAction:^{
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
connection.errorBehavior = FBRequestConnectionErrorBehaviorReconnectSession
| FBRequestConnectionErrorBehaviorAlertUser
| FBRequestConnectionErrorBehaviorRetry;
[connection addRequest:[FBRequest requestForPostStatusUpdate:update.text]
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:update.text result:result error:error];
self.buttonPostStatus.enabled = YES;
}];
[connection start];
self.buttonPostStatus.enabled = NO;
}];
}
- (void)showAlert:(NSString *)message
result:(id)result
error:(NSError *)error {
NSString *alertMsg;
NSString *alertTitle;
if (error) {
alertTitle = #"Error";
if (error.fberrorUserMessage && FBSession.activeSession.isOpen) {
alertTitle = nil;
} else {
// Otherwise, use a general "connection problem" message.
alertMsg = #"Operation failed due to a connection problem, retry later.";
}
} else {
NSDictionary *resultDict = (NSDictionary *)result;
alertMsg = [NSString stringWithFormat:#"Successfully posted '%#'.", update.text];
NSString *postId = [resultDict valueForKey:#"id"];
if (!postId) {
postId = [resultDict valueForKey:#"postId"];
}
if (postId) {
alertMsg = [NSString stringWithFormat:#"%#\nPost ID: %#", alertMsg, postId];
}
alertTitle = #"Ho Gya!!";
}
if (alertTitle) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMsg
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
#end
I want to get the user information like username, email id, birthday etc.. whenever the user logs in.
I am trying to get the info of user by this code. Am I correct or not? If something is missing in this code, please provide some coding solution.
You have to set Permission for that
loginview.readPermissions=#[#"email"];
Related
I am try to follow tutorial regarding to ReactiveCocoa from Ray, but somehow the filter function is working since it always goes down to the subscribeNext although I debugged that filter function does go with the return #NO branch.
#import <Accounts/Accounts.h>
#import <Social/Social.h>
#import <ReactiveCocoa/ReactiveCocoa.h>
#import "SearchViewController.h"
typedef NS_ENUM(NSInteger, RWTwitterInstantError) {
RWTwitterInstantErrorAccessDenied,
RWTwitterInstantErrorNoTwitterAccounts,
RWTwitterInstantErrorInvalidResponse
};
static NSString * const RWTwitterInstantDomain = #"TwitterInstant";
#interface SearchViewController ()
{
RACDisposable *requestTwiiterSubscription;
}
#property (strong, nonatomic) ACAccountStore *accountStore;
#property (strong, nonatomic) ACAccountType *twitterAccountType;
#property (weak, nonatomic) IBOutlet UISearchBar *searchBar;
#property (strong, nonatomic) UITextField *searchBarTextField;
#end
#implementation SearchViewController
- (UITextField *)searchBarTextField {
if (!_searchBarTextField) {
for (UIView *view in self.searchBar.subviews) {
for (id deeperView in view.subviews) {
if ([deeperView isKindOfClass:[UITextField class]]) {
_searchBarTextField = deeperView;
}
}
}
}
return _searchBarTextField;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.searchBar.text = #"Co";
__weak SearchViewController *weakSelf = self;
self.accountStore = [[ACAccountStore alloc] init];
self.twitterAccountType = [self.accountStore
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
/**
* The then method waits until a completed event is emitted, then subscribes to the signal returned by its block parameter.
* This effectively passes control from one signal to the next.
*/
requestTwiiterSubscription = [[[[self requestAccessToTwitterSignal]
then:^RACSignal *{
return weakSelf.searchBarTextField.rac_textSignal;
}]
filter:^BOOL(NSString *textString) {
if (textString.length >= 3) {
return #YES;
}
return #NO;
}]
subscribeNext:^(id x) {
NSLog(#"%#", x);
} error:^(NSError *error) {
NSLog(#"An error occurred: %#", error);
}];
}
- (void)dealloc {
[requestTwiiterSubscription dispose];
}
- (RACSignal *)requestAccessToTwitterSignal {
// 1 - define an error
NSError *accessError = [NSError errorWithDomain:RWTwitterInstantDomain
code:RWTwitterInstantErrorAccessDenied
userInfo:nil];
// 2 - create the signal
return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
// 3 - request access to twitter
[self.accountStore
requestAccessToAccountsWithType:self.twitterAccountType
options:nil
completion:^(BOOL granted, NSError *error) {
// 4 - handle the response
if (!granted) {
[subscriber sendError:accessError];
} else {
[subscriber sendNext:nil];
[subscriber sendCompleted];
}
}];
return nil;
}];
}
#end
You have the wrong return values in the filter. You want:
requestTwiiterSubscription = [[[[self requestAccessToTwitterSignal]
then:^RACSignal *{
return weakSelf.searchBarTextField.rac_textSignal;
}]
filter:^BOOL(NSString *textString) {
if (textString.length >= 3) {
return YES;
}
return NO;
}]
subscribeNext:^(id x) {
NSLog(#"%#", x);
} error:^(NSError *error) {
NSLog(#"An error occurred: %#", error);
}];
You were returning NSNumber objects instead of BOOL values.
I made an AR app that recognize image and show the object recognized in an AlertView. In the AlertView I have 2 buttons: Add and Cancel, I'm using the UIAlertViewDelegate to understand which button the user pressed. If the user press the Add button, the object recognized will be stored in an array. I pass this array to another ViewController, in which I set up a TableView. On the bottom of this TableView there's a button "Pay" to go to another ViewController in which I display the total price of the object recognized. From the last ViewController I can press a button to pay the objects I selected by using the AR. Now when I press this button the app close this ViewController and go back to the first ViewController, but the array in which I stored the object that the AR recognized it's full. To delete the content of this array I thought that the best way is to use the delegation methods, so I made this:
PaymentViewController.h
#import <UIKit/UIKit.h>
#protocol PaymentViewControllerDelegate;
#interface PaymentViewController : UIViewController
#property (strong, nonatomic) IBOutlet UILabel *labelTotal;
- (IBAction)buttonClosePaymentVC:(id)sender;
- (IBAction)buttonPay:(id)sender;
#property(nonatomic,strong)NSString *total;
#property(assign) id<PaymentViewControllerDelegate> delegate;
#end
#protocol PaymentViewControllerDelegate <NSObject>
- (void)cleanReportArray;
#end
PaymentViewController.m
#import "PaymentViewController.h"
#interface PaymentViewController () <UIAlertViewDelegate>
#end
#implementation PaymentViewController
#synthesize delegate = _delegate;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.labelTotal.text = self.total;
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)buttonClosePaymentVC:(id)sender {
[self dismissViewControllerAnimated:YES completion:nil];
}
- (IBAction)buttonPay:(id)sender {
NSString *pay = [NSString stringWithFormat:#"Stai per pagare %#, procedi?", self.total];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"HelloMS" message:pay delegate:self cancelButtonTitle:#"Si" otherButtonTitles:#"No", nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
// Procedura per il pagamento e cancellazione del file plist
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:#"objects.plist"];
NSError *error;
if (![[NSFileManager defaultManager]removeItemAtPath:path error:&error]) {
NSLog(#"Errore: %#", error);
}
__weak UIViewController *vcThatPresentedCurrent = self.presentingViewController;
[self dismissViewControllerAnimated:YES completion:^{
[vcThatPresentedCurrent dismissViewControllerAnimated:YES completion:nil];
}];
[self.delegate cleanReportArray];
}
if (buttonIndex == 1) {
// Non deve far nulla: fa scomparire l'UIAlertView
}
}
Here I post to you the method of the class that will use the delegate:
Interface of the ScannerViewController.m
#interface ScannerViewController () <MSScannerSessionDelegate, PaymentViewControllerDelegate, UIActionSheetDelegate, UIAlertViewDelegate>
#property (weak) IBOutlet UIView *videoPreview;
- (IBAction)stopScanner:(id)sender;
#end
In ViewDidLoad I inserted this rows:
PaymentViewController *pay = [[PaymentViewController alloc]init];
[pay setDelegate:self];
And in the ScannerViewController.m I implemented the method I declared in PaymentViewController.h:
- (void)cleanReportArray {
[arrayObjectAdded removeAllObjects];
}
I tested my app on my iPhone, the app works fine until I try to pay the objects I scanned by camera, indeed, I tried to pay the object, but it doesn't clean the array in which I stored the objects scanned.
What's wrong in my code? I used an tutorial on the web to understand better how the delegation method works. I hope you can help me to fix this issue, thank you
UPDATE:
here i will post my ScannerViewController code:
ScannerViewController.h
#import <UIKit/UIKit.h>
#interface ScannerViewController : UIViewController
#end
ScannerViewController.m
#import "ScannerViewController.h"
#import "PaymentViewController.h"
#import "ReportViewController.h"
#import "MSScannerSession.h"
#import "MSResult.h"
#import "XmlReader.h"
static int kMSScanOptions = MS_RESULT_TYPE_IMAGE |
MS_RESULT_TYPE_EAN8 |
MS_RESULT_TYPE_EAN13;
#interface ScannerViewController () <MSScannerSessionDelegate, PaymentViewControllerDelegate, UIActionSheetDelegate, UIAlertViewDelegate>
#property (weak) IBOutlet UIView *videoPreview;
- (IBAction)stopScanner:(id)sender;
#end
#implementation ScannerViewController {
MSScannerSession *_scannerSession;
NSString *nameOfObjectScanned;
XmlReader *reader;
NSMutableArray *arrayObjectAdded;
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
_scannerSession = [[MSScannerSession alloc] initWithScanner:[MSScanner sharedInstance]];
[_scannerSession setScanOptions:kMSScanOptions];
[_scannerSession setDelegate:self];
}
return self;
}
- (void)session:(MSScannerSession *)scanner didScan:(MSResult *)result {
if (!result) {
return;
}
[_scannerSession pause];
NSString *resultStr = nil;
if (result) {
switch ([result getType]) {
case MS_RESULT_TYPE_IMAGE:
resultStr = [NSString stringWithFormat:#"Immagine trovata: %#", [result getValue]];
break;
case MS_RESULT_TYPE_EAN8:
case MS_RESULT_TYPE_EAN13:
resultStr = [NSString stringWithFormat:#"EAN trovato: %#", [result getValue]];
break;
default:
break;
}
}
dispatch_async(dispatch_get_main_queue(), ^{
UIActionSheet *asView = [[UIActionSheet alloc]initWithTitle:resultStr delegate:self cancelButtonTitle:#"OK" destructiveButtonTitle:nil otherButtonTitles:nil, nil];
asView.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
[asView showInView:self.view];
[self addObjectToList:resultStr];
});
}
- (void)addObjectToList:(NSString *)objectName {
// Ricerca dell'oggetto
NSString *object = [objectName substringFromIndex:18];
if ([object isEqualToString:#"Binario_con_coppia"]) {
[self showAlert:object];
}
if ([object isEqualToString:#"Dadi_colorati"]) {
[self showAlert:object];
}
if ([object isEqualToString:#"Dadi_rossi"]) {
[self showAlert:object];
}
if ([object isEqualToString:#"Bici_da_corsa"]) {
[self showAlert:object];
}
}
- (void)showAlert:(NSString*)name {
name = [name stringByReplacingOccurrencesOfString:#"_" withString:#" "];
nameOfObjectScanned = name;
NSString *message = [NSString stringWithFormat:#"Ho riconosciuto questo oggetto: %#, vuoi aggiungerlo al carrello?", name];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"HelloMS" message:message delegate:self cancelButtonTitle:#"Aggiungi" otherButtonTitles:#"Annulla", nil];
[alert show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
NSLog(#"Aggiungi");
for (int i = 0; i < [reader.objArray count]; i++) {
if ([[reader.objArray[i]objectForKey:#"name"] isEqualToString:nameOfObjectScanned]) {
// Salvo il nome dell'oggetto trovato, il prezzo e la descrizione
NSString *name = [reader.objArray[i]objectForKey:#"name"];
NSString *desc = [reader.objArray[i]objectForKey:#"desc"];
NSString *price = [reader.objArray[i]objectForKey:#"price"];
NSDictionary *newObjectAdded = [[NSDictionary alloc]init];
newObjectAdded = #{#"name": name,
#"desc": desc,
#"price": price};
[arrayObjectAdded addObject:newObjectAdded];
}
}
} else {
NSLog(#"Annulla");
}
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
[_scannerSession resume];
}
- (void)viewDidLoad
{
[super viewDidLoad];
arrayObjectAdded = [[NSMutableArray alloc]init];
CALayer *videoPreviewLayer = [self.videoPreview layer];
[videoPreviewLayer setMasksToBounds:YES];
CALayer *captureLayer = [_scannerSession previewLayer];
[captureLayer setFrame:[self.videoPreview bounds]];
[videoPreviewLayer insertSublayer:captureLayer below:[[videoPreviewLayer sublayers] objectAtIndex:0]];
reader = [[XmlReader alloc]init];
[reader parseXml];
[_scannerSession startCapture];
PaymentViewController *pay = [[PaymentViewController alloc]init];
[pay setDelegate:self];
}
- (void)cleanReportArray {
[arrayObjectAdded removeAllObjects];
}
- (void)dealloc {
[_scannerSession stopCapture];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)stopScanner:(id)sender {
ReportViewController *reportVC = [[ReportViewController alloc]initWithNibName:#"ReportViewController" bundle:nil];
reportVC.reportArray = arrayObjectAdded;
[reportVC setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
[self presentViewController:reportVC animated:YES completion:nil];
}
#end
To recognize picture I'm using this AR SDK. I hope you can help me to understand where's my issue
Your problem is that in viewDidLoad you have the code:
PaymentViewController *pay = [[PaymentViewController alloc]init];
[pay setDelegate:self];
this is the last thing you do in that method. So the instance of PaymentViewController that you create and set the delegate on is immediately destroyed (by ARC).
You need to modify your code so that you call setDelegate: on the actual instance of PaymentViewController that is presented on screen as this is the instance that needs to use the delegate (it receives the callback from the alert view).
How could I upload/download a file from/to dropbox? I integrated dropbox applications in my app, but I couldn't upload/download a file.
This is my upload code:
- (NSString *)getDocumentPath
{
NSMutableData * pdfData = [NSMutableData data];
UIGraphicsBeginPDFContextToData(pdfData, self.view.bounds, nil);
UIGraphicsBeginPDFPage();
CGContextRef pdfContext = UIGraphicsGetCurrentContext();
[self.view.layer renderInContext:pdfContext];
UIGraphicsEndPDFContext();
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *path = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"vani.doc"];
[pdfData writeToFile:path atomically:YES];
return path;
}
- (IBAction)upload:(id)sender {
NSString *path = [self getDocumentPath];
NSString * local = [path lastPathComponent];
NSString *destDir = #"/Plist Folder/vani.doc";
[restClient uploadFile:local toPath:destDir withParentRev:nil fromPath:path];
This is for downloading:
restClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
restClient.delegate = self;
NSString *fileName = [NSString stringWithFormat:#"/vani.doc"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path2 = [documentsDirectory stringByAppendingString:
[NSString stringWithFormat:#"%#", fileName]];
//NSLog(#"%#", path2);
[restClient loadFile:fileName intoPath:path2];
Let me help you in this case, I have created Wrapper class for Dropbox find code below used in one of my project. It does not support ARC. Create DropBoxManager header and implementation file
This may be too much for you if you are beginner but try to read whole answer and follow step by step. Let me know in case of any problem, I will help.
Code for DropBoxManager.h
#import <Foundation/Foundation.h>
#import <DropboxSDK/DropboxSDK.h>
#define kDropbox_AppKey #"" // Provide your key here
#define kDropbox_AppSecret #"" // Provide your secret key here
#define kDropbox_RootFolder kDBRootDropbox //Decide level access like root or app
#protocol DropBoxDelegate;
typedef enum
{
DropBoxTypeStatusNone = 0,
DropBoxGetAccountInfo = 1,
DropBoxGetFolderList = 2,
DropBoxCreateFolder = 3,
DropBoxUploadFile = 4
} DropBoxPostType;
#interface DropboxManager : NSObject <DBRestClientDelegate,DBSessionDelegate,UIAlertViewDelegate>
{
UIViewController<DropBoxDelegate> *apiCallDelegate;
DBSession *objDBSession;
NSString *relinkUserId;
DBRestClient *objRestClient;
DropBoxPostType currentPostType;
NSString *strFileName;
NSString *strFilePath;
NSString *strDestDirectory;
NSString *strFolderCreate;
NSString *strFolderToList;
}
#property (nonatomic,retain) DBSession *objDBSession;
#property (nonatomic,retain) NSString *relinkUserId;
#property (nonatomic,assign) UIViewController<DropBoxDelegate> *apiCallDelegate;
#property (nonatomic,retain) DBRestClient *objRestClient;
#property (nonatomic,assign) DropBoxPostType currentPostType;
#property (nonatomic,retain) NSString *strFileName;
#property (nonatomic,retain) NSString *strFilePath;
#property (nonatomic,retain) NSString *strDestDirectory;
#property (nonatomic,retain) NSString *strFolderCreate;
#property (nonatomic,retain) NSString *strFolderToList;
//Singleton
+(id)dropBoxManager;
//Initialize dropbox
-(void)initDropbox;
//Authentication Verification
-(BOOL)handledURL:(NSURL*)url;
-(void)dropboxDidLogin;
-(void)dropboxDidNotLogin;
//Upload file
-(void)uploadFile;
//Download File
-(void)downlaodFileFromSourcePath:(NSString*)pstrSourcePath destinationPath:(NSString*)toPath;
//Create Folder
-(void)createFolder;
//Get Account Information
-(void)loginToDropbox;
-(void)logoutFromDropbox;
-(BOOL)isLoggedIn;
//List Folders
-(void)listFolders;
#end
#protocol DropBoxDelegate <NSObject>
#optional
- (void)finishedLogin:(NSMutableDictionary*)userInfo;
- (void)failedToLogin:(NSString*)withMessage;
- (void)finishedCreateFolder;
- (void)failedToCreateFolder:(NSString*)withMessage;
- (void)finishedUploadFile;
- (void)failedToUploadFile:(NSString*)withMessage;
- (void)finishedDownloadFile;
- (void)failedToDownloadFile:(NSString*)withMessage;
- (void)getFolderContentFinished:(DBMetadata*)metadata;
- (void)getFolderContentFailed:(NSString*)withMessage;
#end
Code for DropBoxManager.m
#import "DropboxManager.h"
#implementation DropboxManager
#synthesize objDBSession,relinkUserId,apiCallDelegate;
#synthesize objRestClient;
#synthesize currentPostType;
#synthesize strFileName;
#synthesize strFilePath;
#synthesize strDestDirectory;
#synthesize strFolderCreate;
#synthesize strFolderToList;
static DropboxManager *singletonManager = nil;
+(id)dropBoxManager
{
if(!singletonManager)
singletonManager = [[DropboxManager alloc] init];
return singletonManager;
}
-(void)initDropbox
{
DBSession* session = [[DBSession alloc] initWithAppKey:kDropbox_AppKey appSecret:kDropbox_AppSecret root:kDropbox_RootFolder];
session.delegate = self;
[DBSession setSharedSession:session];
[session release];
if([[DBSession sharedSession] isLinked] && objRestClient == nil)
{
self.objRestClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
self.objRestClient.delegate = self;
}
}
-(void)checkForLink
{
if(![[DBSession sharedSession] isLinked])
[[DBSession sharedSession] linkFromController:apiCallDelegate];
}
-(BOOL)handledURL:(NSURL*)url
{
BOOL isLinked=NO;
if ([[DBSession sharedSession] handleOpenURL:url])
{
if([[DBSession sharedSession] isLinked])
{
isLinked=YES;
[self dropboxDidLogin];
}
else
{
isLinked = NO;
[self dropboxDidNotLogin];
}
}
return isLinked;
}
#pragma mark -
#pragma mark Handle login
-(void)dropboxDidLogin
{
NSLog(#"Logged in");
if([[DBSession sharedSession] isLinked] && self.objRestClient == nil)
{
self.objRestClient = [[DBRestClient alloc] initWithSession:[DBSession sharedSession]];
self.objRestClient.delegate = self;
}
switch(currentPostType)
{
case DropBoxTypeStatusNone:
break;
case DropBoxGetAccountInfo:
[self loginToDropbox];
break;
case DropBoxGetFolderList:
[self listFolders];
break;
case DropBoxCreateFolder:
[self createFolder];
break;
case DropBoxUploadFile:
[self uploadFile];
break;
}
//[(MainViewController*)apiCallDelegate setLoginStatus];
}
-(void)dropboxDidNotLogin
{
NSLog(#"Not Logged in");
switch(currentPostType)
{
case DropBoxTypeStatusNone:
break;
case DropBoxUploadFile:
if([self.apiCallDelegate respondsToSelector:#selector(failedToUploadFile:)])
[self.apiCallDelegate failedToUploadFile:#"Problem connecting dropbox. Please try again later."];
break;
case DropBoxGetFolderList:
break;
case DropBoxCreateFolder:
break;
case DropBoxGetAccountInfo:
break;
}
}
#pragma mark -
#pragma mark DBSessionDelegate methods
- (void)sessionDidReceiveAuthorizationFailure:(DBSession*)session userId:(NSString *)userId
{
relinkUserId = [userId retain];
[[[[UIAlertView alloc] initWithTitle:#"Dropbox Session Ended" message:#"Do you want to relink?" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Relink", nil] autorelease] show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)index
{
if (index != alertView.cancelButtonIndex)
[[DBSession sharedSession] linkUserId:relinkUserId fromController:apiCallDelegate];
[relinkUserId release];
relinkUserId = nil;
}
#pragma mark -
#pragma mark Fileupload
-(void)uploadFile
{
if([[DBSession sharedSession] isLinked])
[self.objRestClient uploadFile:strFileName toPath:strDestDirectory withParentRev:nil fromPath:strFilePath];
else
[self checkForLink];
}
-(void)downlaodFileFromSourcePath:(NSString*)pstrSourcePath destinationPath:(NSString*)toPath
{
if([[DBSession sharedSession] isLinked])
[self.objRestClient loadFile:pstrSourcePath intoPath:toPath];
else
[self checkForLink];
}
- (void)restClient:(DBRestClient*)client uploadedFile:(NSString*)destPath from:(NSString*)srcPath metadata:(DBMetadata*)metadata
{
if([self.apiCallDelegate respondsToSelector:#selector(finishedUploadeFile)])
[self.apiCallDelegate finishedUploadFile];
NSLog(#"File uploaded successfully to path: %#", metadata.path);
}
- (void)restClient:(DBRestClient*)client loadedFile:(NSString*)destPath contentType:(NSString*)contentType
{
if([self.apiCallDelegate respondsToSelector:#selector(finishedDownloadFile)])
[self.apiCallDelegate finishedDownloadFile];
}
-(void)restClient:(DBRestClient *)client loadFileFailedWithError:(NSError *)error
{
if([self.apiCallDelegate respondsToSelector:#selector(failedToDownloadFile:)])
[self.apiCallDelegate failedToDownloadFile:[error description]];
}
- (void)restClient:(DBRestClient*)client uploadFileFailedWithError:(NSError*)error
{
if([self.apiCallDelegate respondsToSelector:#selector(failedToUploadFile:)])
[self.apiCallDelegate failedToUploadFile:[error description]];
NSLog(#"File upload failed with error - %#", error);
}
#pragma mark -
#pragma mark Create Folder
-(void)createFolder
{
if([[DBSession sharedSession] isLinked])
[self.objRestClient createFolder:strFolderCreate];
else
[self checkForLink];
}
- (void)restClient:(DBRestClient*)client createdFolder:(DBMetadata*)folder
{
if([self.apiCallDelegate respondsToSelector:#selector(finishedCreateFolder)])
[self.apiCallDelegate finishedCreateFolder];
NSLog(#"Folder created successfully to path: %#", folder.path);
}
- (void)restClient:(DBRestClient*)client createFolderFailedWithError:(NSError*)error
{
if([self.apiCallDelegate respondsToSelector:#selector(failedToCreateFolder:)])
[self.apiCallDelegate failedToCreateFolder:[error description]];
NSLog(#"Folder create failed with error - %#", error);
}
#pragma mark -
#pragma mark Load account information
-(void)loginToDropbox
{
if([[DBSession sharedSession] isLinked])
[self.objRestClient loadAccountInfo];
else
[self checkForLink];
}
- (void)restClient:(DBRestClient*)client loadedAccountInfo:(DBAccountInfo*)info
{
if([self.apiCallDelegate respondsToSelector:#selector(finishedLogin:)])
{
NSMutableDictionary *userInfo = [[[NSMutableDictionary alloc] init] autorelease];
[userInfo setObject:info.displayName forKey:#"UserName"];
[userInfo setObject:info.userId forKey:#"UserID"];
[userInfo setObject:info.referralLink forKey:#"RefferelLink"];
[self.apiCallDelegate finishedLogin:userInfo];
}
NSLog(#"Got Information: %#", info.displayName);
}
- (void)restClient:(DBRestClient*)client loadAccountInfoFailedWithError:(NSError*)error
{
if([self.apiCallDelegate respondsToSelector:#selector(failedToLogin:)])
[self.apiCallDelegate failedToLogin:[error description]];
NSLog(#"Failed to get account information with error - %#", error);
}
#pragma mark -
#pragma mark Logout
-(void)logoutFromDropbox
{
[[DBSession sharedSession] unlinkAll];
[self.objRestClient release];
}
#pragma mark -
#pragma mark Check for login
-(BOOL)isLoggedIn
{
return [[DBSession sharedSession] isLinked] ? YES : NO;
}
#pragma mark -
#pragma mark Load Folder list
-(void)listFolders
{
NSLog(#"Here-->%#",self.strFolderToList);
if([[DBSession sharedSession] isLinked])
[self.objRestClient loadMetadata:self.strFolderToList];
else
[self checkForLink];
}
- (void)restClient:(DBRestClient*)client loadedMetadata:(DBMetadata*)metadata
{
if (metadata.isDirectory)
{
NSLog(#"Folder '%#' contains:", metadata.contents);
for (DBMetadata *file in metadata.contents)
{
NSLog(#"\t%#", file);
}
if([apiCallDelegate respondsToSelector:#selector(getFolderContentFinished:)])
[apiCallDelegate getFolderContentFinished:metadata];
}
NSLog(#"Folder list success: %#", metadata.path);
}
- (void)restClient:(DBRestClient*)client metadataUnchangedAtPath:(NSString*)path
{
}
- (void)restClient:(DBRestClient*)client loadMetadataFailedWithError:(NSError*)error
{
NSLog(#"Load meta data failed with error - %#", error);
if([apiCallDelegate respondsToSelector:#selector(getFolderContentFailed:)])
[apiCallDelegate getFolderContentFailed:[error localizedDescription]];
}
E.g. usage header file
//Your view controller Header file.
#import <UIKit/UIKit.h>
#import "DropboxManager.h"
#interface YourViewController : UIViewController <DropBoxDelegate>
{
DropboxManager *objManager;
}
#property (nonatomic,assign) DropboxManager *objManager;
-(IBAction)btnUploadFileTapped:(id)sender;
#end
E.g. usage implementation file
#import "YourViewController.h"
#implementation YourViewController
#synthesize objManager;
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
objManager = [DropboxManager dropBoxManager];
objManager.apiCallDelegate =self;
[objManager initDropbox];
}
-(IBAction)btnUploadFileTapped:(id)sender
{
objManager.currentPostType = DropBoxUploadFile;
objManager.strFileName = #"YourFileName";
objManager.strFilePath = #"YourFilePath";
objManager.strDestDirectory = #"/";
[objManager uploadFile];
}
#pragma mark -
#pragma mark File upload delegate
- (void)finishedUploadFile
{
NSLog(#"Uploaded successfully.");
}
- (void)failedToUploadFile:(NSString*)withMessage
{
NSLog(#"Failed to upload error is %#",withMessage);
}
#end
Just add
import UIKit/UIKit.h
wherever you are getting error other than ARC.
I'm following the tutorial at:
http://mobile.tutsplus.com/tutorials/iphone/building-a-jabber-client-for-ios-server-setup/ to set up an iOS app with an ejabberd server. So far I have pretty much copied the code over to a new project.
My problem is that the XMPP delegate functions AppDelegate.m are not being called when run on the phone. Everything works fine in Simulator and the two functions below are called.
- (void)xmppStreamDidConnect:(XMPPStream *)sender {
NSLog(#"in WSAppDelegate - xmppStreamDidConnect");
isOpen = YES;
NSError *error = nil;
[[self xmppStream] authenticateWithPassword:password error:&error];
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender {
NSLog(#"in WSAppDelegate - xmppStreamDidAuthenticate");
[self goOnline];
}
I am able to connect on both the phone and simulator as this call runs without error:
[xmppStream connect:&error]
Here is my AppDelegate.h code:
#import <UIKit/UIKit.h>
#import "XMPPRoster.h"
#import "XMPP.h"
#import "SMChatDelegate.h"
#import "SMMessageDelegate.h"
#class SMBuddyListViewController;
#interface WSAppDelegate : NSObject <UIApplicationDelegate> {
UIWindow *window;
SMBuddyListViewController *viewController;
XMPPStream *xmppStream;
XMPPRoster *xmppRoster;
NSString *password;
BOOL isOpen;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet SMBuddyListViewController *viewController;
#property (nonatomic, readonly) XMPPStream *xmppStream;
#property (nonatomic, readonly) XMPPRoster *xmppRoster;
#property (nonatomic, assign) id _chatDelegate;
#property (nonatomic, assign) id _messageDelegate;
- (BOOL)connect;
- (void)disconnect;
#end
And AppDelegate.m:
#import "WSBuddyListViewController.h"
#interface WSAppDelegate()
- (void)setupStream;
- (void)goOnline;
- (void)goOffline;
#end
#implementation WSAppDelegate
#synthesize xmppStream;
#synthesize xmppRoster;
#synthesize window;
#synthesize viewController;
#synthesize _chatDelegate;
#synthesize _messageDelegate;
- (void)applicationWillResignActive:(UIApplication *)application {
[self disconnect];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[self setupStream];
BOOL connected = NO;
connected = [self connect];
NSLog(#"*** connected = %i", connected);
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
return YES;
}
- (void)setupStream {
NSLog(#"in WSAppDelegate - setupStream");
xmppStream = [[XMPPStream alloc] init];
[xmppStream addDelegate:self delegateQueue:dispatch_get_main_queue()];
[xmppStream setHostName:#"localhost"];
}
- (void)goOnline {
NSLog(#"in WSAppDelegate - goOnline");
XMPPPresence *presence = [XMPPPresence presence];
[[self xmppStream] sendElement:presence];
}
- (void)goOffline {
XMPPPresence *presence = [XMPPPresence presenceWithType:#"unavailable"];
[[self xmppStream] sendElement:presence];
}
- (BOOL)connect {
NSLog(#"in WSAppDelegate - connect");
[self setupStream];
NSString *jabberID = [[NSUserDefaults standardUserDefaults] stringForKey:#"userID"];
NSString *myPassword = [[NSUserDefaults standardUserDefaults] stringForKey:#"userPassword"];
if (![xmppStream isDisconnected]) {
NSLog(#"in WSAppDelegate - connect - if (![xmppStream isDisconnected]) ");
return YES;
}
if (jabberID == nil || myPassword == nil) {
NSLog(#"in WSAppDelegate - connect - if (jabberID == nil || myPassword == nil)");
return NO;
}
[xmppStream setMyJID:[XMPPJID jidWithString:jabberID]];
password = myPassword;
NSError *error = nil;
if (![xmppStream connect:&error])
{
NSLog(#"in WSAppDelegate - connect - if (![xmppStream connect:&error]))");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"Can't connect to server %#", [error localizedDescription]]
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
return NO;
}
return YES;
}
- (void)disconnect {
[self goOffline];
[xmppStream disconnect];
[_chatDelegate didDisconnect];
}
#pragma mark -
#pragma mark XMPP delegates
- (void)xmppStreamDidConnect:(XMPPStream *)sender {
NSLog(#"in WSAppDelegate - xmppStreamDidConnect");
isOpen = YES;
NSError *error = nil;
[[self xmppStream] authenticateWithPassword:password error:&error];
}
- (void)xmppStreamDidAuthenticate:(XMPPStream *)sender {
NSLog(#"in WSAppDelegate - xmppStreamDidAuthenticate");
[self goOnline];
}
- (BOOL)xmppStream:(XMPPStream *)sender didReceiveIQ:(XMPPIQ *)iq {
return NO;
}
- (void)xmppStream:(XMPPStream *)sender didReceiveMessage:(XMPPMessage *)message {
NSLog(#"in WSAppDelegate - xmppStream:(XMPPStream *)sender didReceiveMessage");
NSString *msg = [[message elementForName:#"body"] stringValue];
NSString *from = [[message attributeForName:#"from"] stringValue];
NSMutableDictionary *m = [[NSMutableDictionary alloc] init];
[m setObject:msg forKey:#"msg"];
[m setObject:from forKey:#"sender"];
[_messageDelegate newMessageReceived:m];
}
- (void)xmppStream:(XMPPStream *)sender didReceivePresence:(XMPPPresence *)presence {
NSLog(#"in WSAppDelegate - xmppStream:(XMPPStream *)sender didReceivePresence:");
NSString *presenceType = [presence type]; // online/offline
NSString *myUsername = [[sender myJID] user];
NSString *presenceFromUser = [[presence from] user];
if (![presenceFromUser isEqualToString:myUsername]) {
if ([presenceType isEqualToString:#"available"]) {
[_chatDelegate newBuddyOnline:[NSString stringWithFormat:#"%##%#", presenceFromUser, #"localhost"]];
} else if ([presenceType isEqualToString:#"unavailable"]) {
[_chatDelegate buddyWentOffline:[NSString stringWithFormat:#"%##%#", presenceFromUser, #"localhost"]];
}
}
}
- (void)dealloc {
[xmppStream removeDelegate:self];
[xmppRoster removeDelegate:self];
[xmppStream disconnect];
}
#end
If you look at your setupStream method, you are using the name "localhost." This is leading me to believe the server is on your development machine, and the device is trying to connect to itself (localhost). You will have to replace that with your server name.
This likely works in the simulator because the the client and server are one and the same.
UPDATE:
I just read through the tutorial, and it does not do a good job at all at describing how it would work on real device.
as Mike D said, you're connecting to the server which is on your machine([xmppStream setHostName:#"localhost"];)
In order to connect to the "localhost" you have to change hosts file on your device(/etc/hosts), but that is forbidden by Apple, since your app cant change stuff outside the sandbox.(unless the device is jailbroken).
I've done this stuff on an android phone, when faced similar problem in the past.
Check this discussion(Does hosts file exist on the iPhone? How to change it?)
I'm attempting to implement the latest Facebook Connect SDK and I'm having some troubles. For some reason the delegate callbacks for FBSessionDelegate protocol are not being fired. I've followed the instructions on the git Facebook page and tried to mimic the Facebook sample app but no luck. I'm going crazy here so I'm gonna post my code and maybe somebody will see something silly that I've missed.
#import <Foundation/Foundation.h>
#import "FBConnect.h"
#interface FacebookWrapper : UIViewController <FBSessionDelegate, FBRequestDelegate, FBDialogDelegate>{
Facebook* _facebook;
NSArray* _permissions;
}
#property(readonly) Facebook *facebook;
- (void)login;
#end
#import "FacebookWrapper.h"
static NSString* kAppId = #"1234455667778";
#implementation FacebookWrapper
#synthesize facebook = _facebook;
- (id)init {
if (self = [super init]) {
_permissions = [[NSArray arrayWithObjects: #"read_stream", #"offline_access",nil] retain];
_facebook = [[Facebook alloc] initWithAppId:kAppId];
}
return self;
}
- (void)dealloc {
[_facebook release];
[_permissions release];
[super dealloc];
}
- (void)login {
[_facebook authorize:_permissions delegate:self];
}
- (void)fbDidLogin {
NSLog(#"Did Log In");
}
- (void)fbDidNotLogin:(BOOL)cancelled {
NSLog(#"Failed to log in");
}
- (void)fbDidLogout {
NSLog(#"Logged Out");
}
And to call this from another class,
FacebookWrapper *fw = [[FacebookWrapper alloc] init];
[fw login];
The behavior that I'm seeing on the phone is as expected. The Facebook app launches on init and permissions are requested. The phone then brings my app back to the foreground but the delegates for FBSessionDelegate are never fired. I've tried this in the Facebook sample app using my app ID and it worked fine. I have no idea what the difference is.
I figured out the problem. In the App Delegate you need to override handleOpenURL.
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
return [[facebookWrapper facebook] handleOpenURL:url];
}
If you're creating a wrapper class as I am you'll need an instance of it in the app delegate so you can call the hanleOpenURL method in the Facebook class. Also notice that there is a public readonly property for my Facebook instance in my FacebookWrapper class so I can call handlOpenURL.
By doing this your app will know where to continue when it returns from getting permissions inside of the Facebook app.
I have developed wrapper class which will be very helpful to you.
First download latest SDK of Facebook.
Create one class named as "FacebookHelper"
Add following code in .h file:
#import <Foundation/Foundation.h>
#import "FBConnect.h"
#protocol FBApiCallDelegate;
typedef enum FBApiCallType
{
FBApiCallNone = 0,
FBApiCallGetUserInfo = 1,
FBApiCallGetUserFriend = 2,
FBApiCallPostMessage = 3,
FBApiCallPostPicture = 4,
FBApiCallShareLink = 5,
FBApiCallPostAll = 6,
FBApiCallPostMessageFriendWall = 7
} FBApiCallType;
#interface FacebookHelper : NSObject<FBRequestDelegate, FBDialogDelegate, FBSessionDelegate> {
Facebook *objFacebook;
NSArray *arrPermission;
id<FBApiCallDelegate> apiCallDelegate;
FBApiCallType currentApiCallType;
NSString *strMessage;
NSString *strUrlTitle;
NSString *strUrl;
NSString *strCaption;
NSString *strPictureUrl;
UIImage *image;
}
#property(readonly) Facebook *objFacebook;
#property (nonatomic, assign) id<FBApiCallDelegate> apiCallDelegate;
#property (nonatomic, assign) FBApiCallType currentApiCallType;
#property (nonatomic, retain) NSString *strMessage;
#property (nonatomic, retain) NSString *strUrlTitle;
#property (nonatomic, retain) NSString *strUrl;
#property (nonatomic, retain) NSString *strCaption;
#property (nonatomic, retain) NSString *strPictureUrl;
#property (nonatomic, retain) UIImage *image;
+ (FacebookHelper *) sharedInstance;
- (void)releaseObjects;
//Store Authentication
- (void)storeAuthData:(NSString *)accessToken expiresAt:(NSDate *)expiresAt;
- (void)removeAuthData;
//Public Methods
-(BOOL)isLoggedIn;
-(void)loginToFacebook;
-(void)logoutFromFacebook;
//Facebook Methods
-(void)getUserInfo; //Get User Info
-(void)getUserFriends; //Get User's Friend List
-(void)postMessageToWall; //Post Message to FB Wall
-(void)postPictureToWall; //Post Picture to FB Wall
-(void)shareLinkOnWall; //Share Link on FB Wall
-(void)postAllToWall; //Post All - Message, Link, Caption, PhotoUrl
-(void)postMessageToFriendWall; //Post Message to Friend Wall
//String Methods
- (BOOL)isEmptyString:(NSString *)strValue;
- (NSString *) trimWhiteSpace:(NSString *)strValue;
// Default AlertView
-(void)showAlertView:(NSString *)pstrTitle withMessage:(NSString *)pstrMessage delegate:(id)pDelegate;
#end
#protocol FBApiCallDelegate <NSObject>
#optional
//Get User Info Delegate
-(void)finishUserInfoResponse:(id)result;
-(void)failedUserInfoResponse:(NSError *)error;
//Get User's Friend List
-(void)finishUserFriendResponse:(id)result;
-(void)failedUserFriendResponse:(NSError *)error;
//Post Message to FB Wall Delegate
-(void)finishPostMessageResponse:(id)result;
-(void)failedPostMessageResponse:(NSError *)error;
//Post Picture to FB Wall
-(void)finishPostPictureResponse:(id)result;
-(void)failedPostPictureResponse:(NSError *)error;
//Share Link on FB Wall
-(void)finishShareLinkResponse:(id)result;
-(void)failedShareLinkResponse:(NSError *)error;
//Post All - Message, Link, Caption, PhotoUrl
-(void)finishPostAllResponse:(id)result;
-(void)failedPostAllResponse:(NSError *)error;
//Post Message to Friend Wall Delegate
-(void)finishPostMsgFriendWallResponse:(id)result;
-(void)failedPostMsgFriendWallResponse:(NSError *)error;
#end
Add following code in .m file:
#import "FacebookHelper.h"
#implementation FacebookHelper
#synthesize objFacebook;
#synthesize apiCallDelegate, currentApiCallType;
#synthesize strMessage, strUrlTitle, strUrl, strCaption, strPictureUrl, image;
#pragma mark -
#pragma mark Singleton Variables
static FacebookHelper *singletonHelper = nil;
#pragma mark -
#pragma mark Singleton Methods
- (id)init {
if (!g_kFacebookAppId) {
NSLog(#"%#", msgFBAppIDMissing);
exit(1);
return nil;
}
if ((self = [super init])) {
arrPermission = [[NSArray arrayWithObjects: #"read_stream", #"publish_stream", #"offline_access", #"email", #"read_friendlists", #"friends_birthday",nil] retain];
}
return self;
}
+ (FacebookHelper *)sharedInstance {
#synchronized(self) {
if (singletonHelper == nil) {
[[self alloc] init]; // assignment not done here
}
}
return singletonHelper;
}
+ (id)allocWithZone:(NSZone *)zone {
#synchronized(self) {
if (singletonHelper == nil) {
singletonHelper = [super allocWithZone:zone];
// assignment and return on first allocation
return singletonHelper;
}
}
// on subsequent allocation attempts return nil
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 {
- (void)dealloc {
[self releaseObjects];
[super dealloc];
}
- (id)autorelease {
return self;
}
- (void)releaseObjects {
[self.strMessage release];
[self.strUrlTitle release];
[self.strUrl release];
[self.strCaption release];
[self.strPictureUrl release];
[self.image release];
[objFacebook release];
objFacebook = nil;
}
#pragma mark -
#pragma mark FBDelegate(FBSessionDelegate) Methods
/**
* Called when the user has logged in successfully.
*/
- (void)fbDidLogin {
NSLog(#"FB login OK");
[self storeAuthData:objFacebook.accessToken expiresAt:objFacebook.expirationDate];
switch(currentApiCallType)
{
case FBApiCallGetUserInfo:
[self getUserInfo];
break;
case FBApiCallGetUserFriend:
[self getUserFriends];
break;
case FBApiCallPostMessage:
[self postMessageToWall];
break;
case FBApiCallPostPicture:
[self postPictureToWall];
break;
case FBApiCallShareLink:
[self shareLinkOnWall];
break;
case FBApiCallPostAll:
[self postAllToWall];
break;
case FBApiCallPostMessageFriendWall:
[self postMessageToFriendWall];
break;
}
}
/**
* Called when the user canceled the authorization dialog.
*/
-(void)fbDidNotLogin:(BOOL)cancelled {
NSLog(#"FB did not login");
[self removeAuthData];
}
/**
* Called when the request logout has succeeded.
*/
- (void)fbDidLogout {
NSLog(#"FB logout OK");
[self removeAuthData];
}
-(void)fbDidExtendToken:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
NSLog(#"token extended");
[self storeAuthData:accessToken expiresAt:expiresAt];
}
/**
* Called when the session has expired.
*/
- (void)fbSessionInvalidated {
[self showAlertView:msgFBSessionInvalidateTitle withMessage:msgFBSessionInvalidateMessage delegate:nil];
[self fbDidLogout];
}
#pragma mark -
#pragma mark FBRequestDelegate Methods
/**
* Called when the Facebook API request has returned a response. This callback
* gives you access to the raw response. It's called before
* (void)request:(FBRequest *)request didLoad:(id)result,
* which is passed the parsed response object.
*/
- (void)request:(FBRequest *)request didReceiveResponse:(NSURLResponse *)response {
NSLog(#"received response");
}
/**
* Called when a request returns and its response has been parsed into
* an object. The resulting object may be a dictionary, an array, a string,
* or a number, depending on the format of the API response. If you need access
* to the raw response, use:
*
* (void)request:(FBRequest *)request
* didReceiveResponse:(NSURLResponse *)response
*/
- (void)request:(FBRequest *)request didLoad:(id)result {
NSLog(#"FB request OK");
switch(currentApiCallType)
{
case FBApiCallGetUserInfo:
if([self.apiCallDelegate respondsToSelector:#selector(finishUserInfoResponse:)])
[self.apiCallDelegate finishUserInfoResponse:result];
break;
case FBApiCallGetUserFriend:
if ([self.apiCallDelegate respondsToSelector:#selector(finishUserFriendResponse:)])
[self.apiCallDelegate finishUserFriendResponse:result];
break;
case FBApiCallPostMessage:
if ([self.apiCallDelegate respondsToSelector:#selector(finishPostMessageResponse:)])
[self.apiCallDelegate finishPostMessageResponse:result];
break;
case FBApiCallPostPicture:
if ([self.apiCallDelegate respondsToSelector:#selector(finishPostPictureResponse:)])
[self.apiCallDelegate finishPostPictureResponse:result];
break;
case FBApiCallShareLink:
if ([self.apiCallDelegate respondsToSelector:#selector(finishShareLinkResponse:)])
[self.apiCallDelegate finishShareLinkResponse:result];
break;
case FBApiCallPostAll:
if ([self.apiCallDelegate respondsToSelector:#selector(finishPostAllResponse:)])
[self.apiCallDelegate finishPostAllResponse:result];
break;
case FBApiCallPostMessageFriendWall:
if ([self.apiCallDelegate respondsToSelector:#selector(finishPostMsgFriendWallResponse:)])
[self.apiCallDelegate finishPostMsgFriendWallResponse:result];
break;
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
currentApiCallType = FBApiCallNone;
}
/**
* Called when an error prevents the Facebook API request from completing
* successfully.
*/
/*- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(#"FB error: %#", [error localizedDescription]);
}*/
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(#"Err message: %#", [[error userInfo] objectForKey:#"error_msg"]);
/*NSLog(#"Err code: %#", [error code]);
NSLog(#"Err desc: %#", [error description]);
NSLog(#"FB error: %#", [error localizedDescription]);*/
switch(currentApiCallType)
{
case FBApiCallGetUserInfo:
if ([self.apiCallDelegate respondsToSelector:#selector(failedUserInfoResponse:)])
[self.apiCallDelegate failedUserInfoResponse:error];
break;
case FBApiCallGetUserFriend:
if ([self.apiCallDelegate respondsToSelector:#selector(failedUserFriendResponse:)])
[self.apiCallDelegate failedUserFriendResponse:error];
break;
case FBApiCallPostMessage:
if ([self.apiCallDelegate respondsToSelector:#selector(failedPostMessageResponse:)])
[self.apiCallDelegate failedPostMessageResponse:error];
break;
case FBApiCallPostPicture:
if ([self.apiCallDelegate respondsToSelector:#selector(failedPostPictureResponse:)])
[self.apiCallDelegate failedPostPictureResponse:error];
break;
case FBApiCallShareLink:
if ([self.apiCallDelegate respondsToSelector:#selector(failedShareLinkResponse:)])
[self.apiCallDelegate failedShareLinkResponse:error];
break;
case FBApiCallPostAll:
if ([self.apiCallDelegate respondsToSelector:#selector(failedPostAllResponse:)])
[self.apiCallDelegate failedPostAllResponse:error];
case FBApiCallPostMessageFriendWall:
if ([self.apiCallDelegate respondsToSelector:#selector(failedPostMsgFriendWallResponse:)])
[self.apiCallDelegate failedPostMsgFriendWallResponse:error];
break;
}
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
currentApiCallType = FBApiCallNone;
}
/**
* Called when a UIServer Dialog successfully return.
*/
- (void)dialogDidComplete:(FBDialog *)dialog {
NSLog(#"Published successfully on FB");
}
#pragma mark -
#pragma mark Store/Remove Authentication
- (void)storeAuthData:(NSString *)accessToken expiresAt:(NSDate *)expiresAt {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:accessToken forKey:g_kFacebookAccessToken];
[defaults setObject:expiresAt forKey:g_kFacebookExpirationDate];
[defaults synchronize];
}
- (void)removeAuthData{
// Remove saved authorization information if it exists and it is
// ok to clear it (logout, session invalid, app unauthorized)
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults removeObjectForKey:g_kFacebookAccessToken];
[defaults removeObjectForKey:g_kFacebookExpirationDate];
[defaults synchronize];
/*
[[NSUserDefaults standardUserDefaults] setObject:#"" forKey:g_kFacebookAccessToken];
[[NSUserDefaults standardUserDefaults] setObject:#"" forKey:g_kFacebookExpirationDate];
[[NSUserDefaults standardUserDefaults] synchronize];*/
/*
[[NSUserDefaults standardUserDefaults] setObject:nil forKey:g_kFacebookAccessToken];
[[NSUserDefaults standardUserDefaults] setObject:nil forKey:g_kFacebookExpirationDate];
[[NSUserDefaults standardUserDefaults] synchronize];*/
}
#pragma mark -
#pragma mark Public Methods
-(BOOL)isLoggedIn
{
if(objFacebook == nil)
objFacebook = [[[Facebook alloc] initWithAppId:g_kFacebookAppId andDelegate:self] retain];
NSString *strAccessToken = [[NSUserDefaults standardUserDefaults] stringForKey:g_kFacebookAccessToken];
NSLog(#"Access Token = %#", strAccessToken);
//if(![strAccessToken isEmptyString])
if(![self isEmptyString:strAccessToken])
{
objFacebook.accessToken = [[NSUserDefaults standardUserDefaults] stringForKey:g_kFacebookAccessToken];
objFacebook.expirationDate = (NSDate *) [[NSUserDefaults standardUserDefaults] objectForKey:g_kFacebookExpirationDate];
}
if([objFacebook isSessionValid])
return YES;
else
return NO;
return NO;
}
-(void)loginToFacebook
{
if(![self isLoggedIn])
[objFacebook authorize:arrPermission];
}
-(void)logoutFromFacebook {
[objFacebook logout:self];
[self removeAuthData];
[self releaseObjects];
}
#pragma mark -
#pragma mark Facebook Methods
-(void)getUserInfo
{
currentApiCallType = FBApiCallGetUserInfo;
if([self isLoggedIn])
{
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"name,picture",#"fields",nil];
[objFacebook requestWithGraphPath:#"me" andParams:params andDelegate:self];
}
else
[self loginToFacebook];
}
-(void)getUserFriends
{
currentApiCallType = FBApiCallGetUserFriend;
if([self isLoggedIn])
{
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"picture,id,name,birthday,link,gender,last_name,first_name",#"fields",nil];
[objFacebook requestWithGraphPath:#"me/friends" andParams:params andDelegate:self];
}
else
[self loginToFacebook];
}
-(void)postMessageToWall
{
currentApiCallType = FBApiCallPostMessage;
if([self isLoggedIn])
{
NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
[params setObject:#"status" forKey:#"type"];
[params setObject:self.strMessage forKey:#"message"];
[objFacebook requestWithGraphPath:#"me/feed" andParams:params andHttpMethod:#"POST" andDelegate:self];
}
else
[self loginToFacebook];
}
-(void)postPictureToWall
{
currentApiCallType = FBApiCallPostPicture;
if([self isLoggedIn])
{
NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
[params setObject:self.image forKey:#"source"];
[params setObject:self.strMessage forKey:#"message"];
[objFacebook requestWithGraphPath:#"me/photos" andParams:params andHttpMethod:#"POST" andDelegate:self];
}
else
[self loginToFacebook];
}
-(void)shareLinkOnWall
{
currentApiCallType = FBApiCallShareLink;
if([self isLoggedIn])
{
NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
[params setObject:#"link" forKey:#"type"];
[params setObject:self.strUrl forKey:#"link"];
[params setObject:self.strMessage forKey:#"description"];
[objFacebook requestWithGraphPath:#"me/feed" andParams:params andHttpMethod:#"POST" andDelegate:self];
}
else
[self loginToFacebook];
}
-(void)postAllToWall
{
currentApiCallType = FBApiCallPostAll;
if([self isLoggedIn])
{
NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
[params setObject:self.strMessage forKey:#"description"];
[params setObject:self.strUrlTitle forKey:#"name"];
[params setObject:self.strUrl forKey:#"link"];
[params setObject:self.strCaption forKey:#"caption"];
[params setObject:self.strPictureUrl forKey:#"picture"];
[objFacebook requestWithGraphPath:#"me/feed" andParams:params andHttpMethod:#"POST" andDelegate:self];
}
else
[self loginToFacebook];
}
-(void)postMessageToFriendWall
{
currentApiCallType = FBApiCallPostMessageFriendWall;
if([self isLoggedIn])
{
NSString *strGraphPath = [NSString stringWithFormat:#"%#/feed", #"100002305497328"];
//NSString *strGraphPath = [NSString stringWithFormat:#"%#/feed", #"100002560928461"];
NSMutableDictionary *params = [[[NSMutableDictionary alloc] init] autorelease];
[params setObject:self.strMessage forKey:#"message"];
[objFacebook requestWithGraphPath:strGraphPath andParams:params andHttpMethod:#"POST" andDelegate:self];
}
else
[self loginToFacebook];
}
#pragma mark -
#pragma mark String Methods
- (BOOL)isEmptyString:(NSString *)strValue
{
NSString *copy;
if (strValue == nil)
return (YES);
if ([strValue isEqualToString:#""])
return (YES);
if ([strValue isEqualToString:#"(null)"])
return (YES);
copy = [[strValue copy] autorelease];
//if ([[copy trimWhiteSpace] isEqualToString: #""])
if ([[self trimWhiteSpace:copy] isEqualToString: #""])
return (YES);
return (NO);
} /*stringIsEmpty*/
- (NSString *) trimWhiteSpace:(NSString *)strValue
{
NSMutableString *s = [[strValue mutableCopy] autorelease];
CFStringTrimWhitespace ((CFMutableStringRef) s);
return (NSString *) [[s copy] autorelease];
} /*trimWhiteSpace*/
#pragma mark -
#pragma mark Default AlertView
-(void)showAlertView:(NSString *)pstrTitle withMessage:(NSString *)pstrMessage delegate:(id)pDelegate
{
UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:pstrTitle message:pstrMessage delegate:pDelegate cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
#end
That's it. Now our Facebook wrapper class is ready.
Create 3 below class for better organization.
FacebookGlobal.h
Add below data:
#define g_kFacebookAppId #"<Your AppID>"
#define g_kFacebookAppSecret #"<Your Secret>"
#define g_kPostMessage #"<Message>"
#define g_kPostUrlTitle #"<Title>"
#define g_kPostUrl #"<Url>"
#define g_kPostCaption #"<Caption>"
#define g_kPostPictureUrl #"<Image Url>"
FacebookKey.h
Add below data:
#define g_kFacebookAccessToken #"FBAccessTokenKey"
#define g_kFacebookExpirationDate #"FBExpirationDateKey"
FacebookMessage.h
Add below data:
//AppID Missing
#define msgFBAppIDMissing #"Missing AppID"
//Session Invalidated
#define msgFBSessionInvalidateTitle #"Auth Exception"
#define msgFBSessionInvalidateMessage #"Your session has expired."
Import below files in your .pch files:
#import "FacebookGlobal.h"
#import "FacebookKey.h"
#import "FacebookMessage.h"
#import "FacebookHelper.h"
Now, you are ready for use.
In your view controller, add below delegate:
<FBApiCallDelegate>
In your view controller .m file, add below methods to call as well delegate:
- (void)viewWillAppear:(BOOL)animated {
/*
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
[fbHelper logoutFromFacebook];
*/
//Get User Info
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
[fbHelper getUserInfo];
/*
//Get User's Friend List
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
[fbHelper getUserFriends];
*/
/*
//Post Message to FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
[fbHelper postMessageToWall];
*/
/*
//Post Picture to FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
fbHelper.image = [UIImage imageNamed:#"postPicture.jpg"];
[fbHelper postPictureToWall];
*/
/*
//Share Link on FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strUrl = g_kPostUrl;
fbHelper.strMessage = g_kPostMessage;
[fbHelper shareLinkOnWall];
*/
/*
//Post All to FB Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
fbHelper.strUrlTitle = g_kPostUrlTitle;
fbHelper.strUrl = g_kPostUrl;
fbHelper.strCaption = g_kPostCaption;
fbHelper.strPictureUrl = g_kPostPictureUrl;
[fbHelper postAllToWall];
*/
/*
//Post Message to Friend Wall
FacebookHelper *fbHelper = [FacebookHelper sharedInstance];
fbHelper.apiCallDelegate = self;
fbHelper.strMessage = g_kPostMessage;
[fbHelper postMessageToFriendWall];
*/
}
#pragma mark -
#pragma mark Get User Info Delegate
-(void)finishUserInfoResponse:(id)result{
NSLog(#"UserInfo response successed!");
NSLog(#"%#", result);
}
-(void)failedUserInfoResponse:(NSError *)error{
NSLog(#"UserInfo response failed!");
}
#pragma mark -
#pragma mark Get User's Friend List
-(void)finishUserFriendResponse:(id)result{
NSLog(#"User FriendList response successed!");
NSLog(#"%#", result);
}
-(void)failedUserFriendResponse:(NSError *)error{
NSLog(#"User FriendList response failed!");
}
#pragma mark -
#pragma mark Post Message to FB Wall Delegate
-(void)finishPostMessageResponse:(id)result{
NSLog(#"Post message successed!");
NSLog(#"%#", result);
}
-(void)failedPostMessageResponse:(NSError *)error{
NSLog(#"Post message failed!");
}
#pragma mark -
#pragma mark Post Picture to FB Wall
-(void)finishPostPictureResponse:(id)result{
NSLog(#"Post picture successed!");
NSLog(#"%#", result);
}
-(void)failedPostPictureResponse:(NSError *)error{
NSLog(#"Post picture failed!");
}
#pragma mark -
#pragma mark Share Link on FB Wall
-(void)finishShareLinkResponse:(id)result{
NSLog(#"Share link successed!");
NSLog(#"%#", result);
}
-(void)failedShareLinkResponse:(NSError *)error{
NSLog(#"Share link failed!");
}
#pragma mark -
#pragma mark Post All - Message, Link, Caption, PhotoUrl
-(void)finishPostAllResponse:(id)result{
NSLog(#"Post all successed!");
NSLog(#"%#", result);
}
-(void)failedPostAllResponse:(NSError *)error{
NSLog(#"Post all failed!");
}
#pragma mark -
#pragma mark Post Message to Friend Wall Delegate
-(void)finishPostMsgFriendWallResponse:(id)result{
NSLog(#"Post message to friend wall successed!");
NSLog(#"%#", result);
}
-(void)failedPostMsgFriendWallResponse:(NSError *)error{
NSLog(#"Post message to friend wall failed!");
}
Happy Coding :)
Enjoy.