-1

我已经在我的项目中添加了 FBSdk 以及 SBJson 类,我应该在我的第二个视图控制器中导入哪些文件来运行我的代码?

我想使用 url 下的描述在 Fb 上发布,因此我需要将此代码包含到我的第二个视图控制器中,但我陷入了我发现以下代码应该添加到第二个视图控制器中的部分,但是“委托:自我”不起作用,因为我是第一次这样做,所以任何人都可以指导我如何在我的第二个视图控制器中编码,同时考虑到应用程序委托的值(我应该如何从应用程序委托中获取值FB 到第二个视图,以便我可以在第二个代码中添加此代码,请任何人都可以更正此代码)

facebook = [[Facebook alloc] initWithAppId:@"YOUR_APP_ID"]; 

// 我应该如何从应用程序委托中获取这个 id?

 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];

上面的代码正确吗?我应该如何在 -(void)fb_share (方法)中的第二个视图控制器中实现它。

我的应用程序委托文件是这样的:

#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

任何人都可以通过从委托中获取值来弄清楚我应该在第二个视图控制器的 -(void)fb_share 方法中编写什么代码吗?任何帮助!


我这样做了......并得到错误:HTTP状态代码:400......但用户名显示在警报中

     [[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];

                   }
    }];

.. 我现在该怎么办 ?

4

1 回答 1

1

声明facebookproperty in .h您的文件appDelegate

然后在second view controller导入AppDelegate

在您想要 Facebook 对象的 .m 文件中

得到它喜欢

AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
Facebook *facebook = appDelegate.facebook;
于 2013-01-18T10:56:27.807 回答