ios有没有办法在后台发布facebook和twitter?

时间:2014-03-16 05:44:56

标签: ios objective-c facebook twitter background

我想发送消息并希望在Facebook和Twitter上发布背景是否有任何可能的框架可以做到这一点。任何人都可以分享这个想法。谢谢。

2 个答案:

答案 0 :(得分:1)

要在Twitter上在后台发帖,请使用此库https://github.com/nst/STTwitter

您需要在Twitter上注册您的应用以接收消费者密钥和消费者密钥。完成后,只需使用此处显示的代码Accessing Twitter Direct Messages using SLRequest iOS。此代码使用系统Twitter凭据,用户必须在iPhone / iPad设置中设置这些凭据。

关于Facebook上的帖子:我发现没有iOS的包装器可以提供在后台发布的可能性。我使用官方Facebook iOS SDK https://github.com/facebook/facebook-ios-sdk。但是帖子功能仅适用于用户的参与。

答案 1 :(得分:1)

对于Facebook,请确保您拥有正确的用户权限或sdk设置。我建议您仔细阅读本教程。 http://m-farhan.com/2014/03/ios-facebook-sdk-tutorial/

    - (void)requestPermissionAndPost {
        [FBSession.activeSession requestNewPublishPermissions:[NSArray arrayWithObjects:@"publish_actions", @"publish_checkins",nil]
                                              defaultAudience:FBSessionDefaultAudienceEveryone
                                            completionHandler:^(FBSession *session, NSError *error) {
                                                if (!error) {
                                                    // Now have the permission
                                                    [self postOpenGraphAction];
                                                } else {
                                                    // Facebook SDK * error handling *
                                                    // if the operation is not user cancelled
                                                    if (error.fberrorCategory != FBErrorCategoryUserCancelled) {
                                                        [self presentAlertForError:error];
                                                    }
                                                }
                                            }];
    }
    - (void)postOpenGraphAction
    {
        FBRequestConnection *newConnection = [[FBRequestConnection alloc] init];
        FBRequestHandler handler =
        ^(FBRequestConnection *connection, id result, NSError *error) {
            // output the results of the request
            [self requestCompleted:connection forFbID:@"me" result:result error:error];
        };

        UIImage *img = imageView.image;
        NSString *message = @"Your Message";
        FBRequest *request=[[FBRequest alloc] initWithSession:FBSession.activeSession graphPath:@"me/photos" parameters:[NSDictionary dictionaryWithObjectsAndKeys:UIImageJPEGRepresentation(img, 0.7),@"source",message,@"message",@"{'value':'EVERYONE'}",@"privacy", nil] HTTPMethod:@"POST"];


        [newConnection addRequest:request completionHandler:handler];
        [self.requestConnection cancel];
         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");
        NSLog(@"%@",result);
        /*[[[UIAlertView alloc] initWithTitle:@"Result"
                                    message:[NSString stringWithFormat:@"Posted Open Graph action, id: %@",
                                             [result objectForKey:@"id"]]
                                   delegate:nil
                          cancelButtonTitle:@"Thanks!"
                          otherButtonTitles:nil]
         show];*/
        [self doCheckIn];

    };
}
来自Twitter的简单易用

#import <Twitter/Twitter.h>

 - (void)TWPostImage:(UIImage *)image withStatus:(NSString *)status
    {
        ACAccountStore *accountStore = [[ACAccountStore alloc] init];

        //ACAccountStore *accountStore = [[ACAccountStore alloc] init];

        // Create an account type that ensures Twitter accounts are retrieved.
        ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

        [accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
            ACAccount *ac;
            if(granted) {
                NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
                int i=0;
                for (ACAccount *account in accountsArray ) {
                    i++;
                    NSLog(@"Account name: %@", account.username);
                    ac=account;
                }
                if (i==0) {
                    [[[UIAlertView alloc] initWithTitle:@"Wait"
                                                message:@"Please setup Twitter Account Settigns > Twitter > Sign In "
                                               delegate:nil
                                      cancelButtonTitle:@"Thanks!"
                                      otherButtonTitles:nil]
                     show];
                    return ;

                }

                ACAccountType *twitterType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];;

                //SLRequestHandler requestHandler;

                SLRequestHandler requestHandler =
                ^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                    if (responseData) {
                        NSInteger statusCode = urlResponse.statusCode;
                        if (statusCode >= 200 && statusCode < 300) {
                            NSDictionary *postResponseData =
                            [NSJSONSerialization JSONObjectWithData:responseData
                                                            options:NSJSONReadingMutableContainers
                                                              error:NULL];
                            NSLog(@"[SUCCESS!] Created Tweet with ID: %@", postResponseData[@"id_str"]);
                            ESAppDelegate* d =[[UIApplication sharedApplication] delegate];
                            NSString* link = [NSString stringWithFormat:@"Your Message",twitterAccStore,hashtagFromStore];
                            [d linkSelected:link PointerToSelf:self];
                            /*[[[UIAlertView alloc] initWithTitle:@"Result"
                                                        message:[NSString stringWithFormat:@"[SUCCESS!] Created Tweet with ID: %@", postResponseData[@"id_str"]]
                                                       delegate:nil
                                              cancelButtonTitle:@"Thanks!"
                                              otherButtonTitles:nil]
                             show];*/

                        }
                        else {
                            NSLog(@"[ERROR] Server responded: status code %d %@", statusCode,
                                  [NSHTTPURLResponse localizedStringForStatusCode:statusCode]);
                        }
                    }
                    else {
                        NSLog(@"[ERROR] An error occurred while posting: %@", [error localizedDescription]);
                    }
                    });
                };
                //});
                ACAccountStoreRequestAccessCompletionHandler accountStoreHandler =
                ^(BOOL granted, NSError *error) {
                    if (granted) {
                        NSArray *accounts = [accountStore accountsWithAccountType:twitterType];
                        NSURL *url = [NSURL URLWithString:@"https://api.twitter.com"
                                      @"/1.1/statuses/update_with_media.json"];
                        NSDictionary *params = @{@"status" : status};
                        SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
                                                                requestMethod:SLRequestMethodPOST
                                                                          URL:url
                                                                   parameters:params];
                        NSData *imageData = UIImageJPEGRepresentation(image, 1.f);
                        [request addMultipartData:imageData
                                         withName:@"media[]"
                                             type:@"image/jpeg"
                                         filename:@"image.jpg"];
                        [request setAccount:[accounts lastObject]];

                        [request performRequestWithHandler:requestHandler];
                        //});
                    }
                    else {
                        NSLog(@"[ERROR] An error occurred while asking for user authorization: %@",
                              [error localizedDescription]);
                    }
                };

                [accountStore requestAccessToAccountsWithType:twitterType
                                                      options:NULL
                                                   completion:accountStoreHandler];
            }else
            {
                [[[UIAlertView alloc] initWithTitle:@"Wait"
                                            message:@"Please Settigns > Twitter > In bottom Enable DealsHype to post"
                                           delegate:nil
                                  cancelButtonTitle:@"Thanks!"
                                  otherButtonTitles:nil]
                                    show];
            }
        }];
    }