I'm trying to post an image using the TWRequest object. Here's my code:
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
NSData *pngImage = UIImagePNGRepresentation(image);
NSData *tweetText = [userText copy];
[accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
if (granted) {
NSLog(@"Twitter is good to go");
NSArray *twitterAccounts = [accountStore accountsWithAccountType:accountType];
if (twitterAccounts.count) {
ACAccount *twitterAccount = [twitterAccounts objectAtIndex:0];
NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1.1/statuses/update_with_media.json"];
TWRequest *request = [[TWRequest alloc] initWithURL:url parameters:nil requestMethod:TWRequestMethodPOST];
[request addMultiPartData:pngImage withName:@"media" type:@"image/png"];
[request addMultiPartData:tweetText withName:@"text" type:@"text/plain"];
[request setAccount:twitterAccount];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (responseData)
{
NSError *error = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
if (jsonArray) {
for(NSDictionary *item in jsonArray) {
NSLog(@"Item: %@", item);
}
}
else
{
NSLog(@"Error %@ with user info %@.", error, error.userInfo);
}
}
}];
}
} else {
NSLog(@"The user does not grant us permission to access its Twitter account(s).");
}
}];
Whenever the program reaches the line with [request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
I get the following error:
[__NSCFString bytes]: unrecognized selector sent to instance 0x1d8f4250 * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString bytes]: unrecognized selector sent to instance 0x1d8f4250' * First throw call stack: (0x33ec02a3 0x3bb5a97f 0x33ec3e07 0x33ec2531 0x33e19f68 0x3473b90b 0x35c416fd 0x35c417a3 0x35c4065f 0x35c3fa6b 0x35c40ab9 0x5adc5 0x3bf7211f 0x3bf7fdcb 0x3bf80259 0x3bf803b9 0x3bfa6a11 0x3bfa68a4) libc++abi.dylib: terminate called throwing an exception (lldb)
The problem is with tweetText
. You are copying an NSString
but assigning it to an NSData
object.
Change this:
NSData *tweetText = [userText copy];
to this:
NSData *tweetText = [userText dataUsingEncoding:NSUTF8StringEncoding];