使用Parse框架发布推文

时间:2014-02-24 14:40:57

标签: ios twitter parse-platform

我有问题通过解析框架发布到twitter。我使用此功能登录了我的用户,

[PFTwitterUtils linkUser:[PFUser currentUser]];

然后我尝试使用此帖子发布到Twitter,

NSString *bodyString = @"this is a test";

    // Explicitly percent-escape the '!' character.
    bodyString = [bodyString stringByReplacingOccurrencesOfString:@"!" withString:@"%21"];

    NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/update.json"];
    NSMutableURLRequest *tweetRequest = [NSMutableURLRequest requestWithURL:url];
    tweetRequest.HTTPMethod = @"POST";
    tweetRequest.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];

    [[PFTwitterUtils twitter] signRequest:tweetRequest];

    NSURLResponse *response = nil;
    NSError *error = nil;

    // Post status synchronously.
    NSData *data = [NSURLConnection sendSynchronousRequest:tweetRequest
                                         returningResponse:&response
                                                     error:&error];

    // Handle response.
    if (!error) {
        NSLog(@"Response: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    } else {
        NSLog(@"Error: %@", error);
    }

然后抛出此错误,

Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. 
  (NSURLErrorDomain error -1012.)" UserInfo=0xac5eac0 
 {NSErrorFailingURLKey=https://api.twitter.com/1.1/statuses/update.json,
 NSErrorFailingURLStringKey=https://api.twitter.com/1.1/statuses/update.json,  
 NSUnderlyingError=0xc0945b0 "The operation couldn’t be completed. 
 (kCFErrorDomainCFNetwork error -1012.)"}

任何帮助都会受到大力赞赏!

3 个答案:

答案 0 :(得分:6)

希望这是及时的帮助。

首先,仔细检查您的Twitter API是否启用了读/写身份验证。

其次,您需要在原始文本中包含“status =”前缀。

最后,您需要完整的“%”编码,而不仅仅是“!”。

这是你重构的代码:

NSString *bodyString = @"status=this is a test with spaces";

bodyString = [bodyString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];

NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/update.json"];
NSMutableURLRequest *tweetRequest = [NSMutableURLRequest requestWithURL:url];
tweetRequest.HTTPMethod = @"POST";
tweetRequest.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];

[[PFTwitterUtils twitter] signRequest:tweetRequest];

NSURLResponse *response = nil;
NSError *error = nil;


// Post status synchronously.
NSData *data = [NSURLConnection sendSynchronousRequest:tweetRequest
                                 returningResponse:&response
                                             error:&error];

// Handle response.
if (!error) {
    NSLog(@"Response: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
} else {
    NSLog(@"Error: %@", error);
}

答案 1 :(得分:0)

我已经使用面料试图发布推文并将其作为回复获取,但是,由于Twitter开发团队的回答,当我问是否可能时,这是不允许的,这是#s为什么在这段代码中使用Parse,可以发布推文并获取其ID

if (![PFTwitterUtils isLinkedWithUser:user])
 {
    [PFTwitterUtils linkUser:user block:^(BOOL succeeded, NSError *error) {
        if ([PFTwitterUtils isLinkedWithUser:user]) {
            NSLog(@"Woohoo, user logged in with Twitter!");
            //or put code here to login USER
        }
        else
        {
            [PFTwitterUtils unlinkUserInBackground:user block:^(BOOL succeeded, NSError *error) {
                if (!error && succeeded) {
                    NSLog(@"The user is no longer associated with their Twitter account.");
                }
            }];
        }
    }];
}
 else
{
    // here when user logged in with twitter as a parse user

    NSString *status=@"Success";
    NSString *bodyString = [NSString stringWithFormat:@"status=%@", [status stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

    // Explicitly percent-escape the '!' character.
    bodyString = [bodyString stringByReplacingOccurrencesOfString:@"!" withString:@"%21"];

    NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/update.json"];
    NSMutableURLRequest *tweetRequest = [NSMutableURLRequest requestWithURL:url];
    //[user a]
    // [tweetRequest setValue:@"872557363-aeHtbWHK9DjaHsmo6ogI2PcriigIk0IPa0Hk9gAV" forHTTPHeaderField:@"access_token"];
    tweetRequest.HTTPMethod = @"POST";
    tweetRequest.HTTPBody = [bodyString dataUsingEncoding:NSUTF8StringEncoding];

    [[PFTwitterUtils twitter] signRequest:tweetRequest];

    NSURLResponse *response = nil;
    NSError *error = nil;

    // Post status synchronously.
    NSData *data = [NSURLConnection sendSynchronousRequest:tweetRequest
                                         returningResponse:&response
                                                     error:&error];

    // Handle response.
    if (!error) {

        NSLog(@"Response: %@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
        NSDictionary * parsedData  = [[NSDictionary alloc]init];
        parsedData = [NSJSONSerialization
                      JSONObjectWithData:data //1
                      options:kNilOptions
                      error:&error];
        NSString *tweetId=[parsedData valueForKey:@"id_str"];
        NSLog(@"the hell tweet id = %@",tweetId);

    } else {
        NSLog(@"Error: %@", error);
    }

}

答案 2 :(得分:0)

这是一个Swift版本:

    if !PFTwitterUtils.isLinkedWithUser(user) {
        PFTwitterUtils.linkUser(user, {
            (succeeded: Bool?, error: NSError?) -> Void in
            if PFTwitterUtils.isLinkedWithUser(user) {
                println("Woohoo, user logged in with Twitter!")
                let verify = NSURL(string: "https://api.twitter.com/1.1/account/verify_credentials.json")
                var request = NSMutableURLRequest(URL: verify!)
                PFTwitterUtils.twitter()!.signRequest(request)
                var response: NSURLResponse?
               var error:NSError? = nil
                var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)

                if let jsonObject: AnyObject = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error:&error) {
                    if let dict = jsonObject as? NSDictionary {
                        NSLog("the hell dist =%@", dict)
                    } else {
                        println("not a dictionary")
                    }
                } else {
                    println("Could not parse JSON: \(error!)")
                }
               // dict = NSJSONSerialization.JSONObjectWithData(data, options:, error: NSErrorPointer())

                               }
        })
    }
    else
    {
        var tweetSTr=NSString()
        tweetSTr="tweeted"
        var bodyStr=NSString(format: "status=%@", tweetSTr.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!)
            bodyStr=bodyStr.stringByReplacingOccurrencesOfString("!", withString: "%21")


        var url=NSURL(string: "https://api.twitter.com/1.1/statuses/update.json")
        var tweetRequest=NSMutableURLRequest(URL: url!)
        tweetRequest.HTTPMethod="POST"
        tweetRequest.HTTPBody=bodyStr.dataUsingEncoding(NSUTF8StringEncoding)

        PFTwitterUtils.twitter().signRequest(tweetRequest)
        var response: NSURLResponse?
        var error:NSError? = nil
        var data = NSURLConnection.sendSynchronousRequest(tweetRequest, returningResponse: &response, error: &error)

        if let jsonObject: AnyObject = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error:&error) {
            if let dict = jsonObject as? NSDictionary {
                NSLog("myTweetINfo  =%@", dict)
                var tweetID=NSString()
               tweetID=dict.valueForKey("id_str") as String
                NSLog("myJustPostedTweetID = %@", tweetID)

            } else {
                println("not a dictionary")
            }
        } else {
            println("Could not parse JSON: \(error!)")
        }

    }
相关问题