我想从我的 iOS 应用程序将照片发布到 Twitter。我可以在没有媒体的情况下发布推文,但是当我尝试附加媒体时它会引发错误。
我正在关注 Twitter 文档,根据该文档,我首先需要将媒体上传到 https://upload.twitter.com/1.1/media/upload.json然后我就可以使用 media-id 将其附加到推文中。
这是我上传媒体的代码。
应用在调用 URLRequestWithMedthod 时崩溃。
帮我解决问题。
UIImage *image = [UIImage imageNamed:@"shareit.png"];
NSData *imageData = UIImageJPEGRepresentation(image, 0.7);
NSString *statusesShowEndpoint = @"https://upload.twitter.com/1.1/media/upload.json";
NSDictionary *params = @{@"media" : imageData};
NSError *clientError;
NSURLRequest *request = [[[Twitter sharedInstance] APIClient]
URLRequestWithMethod:@"POST"
URL:statusesShowEndpoint
parameters:params
error:&clientError];
if (request) {
[[[Twitter sharedInstance] APIClient]
sendTwitterRequest:request
completion:^(NSURLResponse *response,
NSData *data,
NSError *connectionError) {
if (data) {
// handle the response data e.g.
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:data
options:0
error:&jsonError];
NSLog(@"%@",json);
}
else {
NSLog(@"Error: %@", connectionError);
}
}];
}
else {
NSLog(@"Error: %@", clientError);
}
最佳答案
其实很简单。所缺少的只是将图像数据转换为 base64EncodedString。这是解决方案。
NSString *media = @"https://upload.twitter.com/1.1/media/upload.json";
NSData *imageData = UIImageJPEGRepresentation(image, 0.9);
NSString *imageString = [imageData base64EncodedStringWithOptions:0];
NSError *error;
NSURLRequest *request = [[[Twitter sharedInstance] APIClient] URLRequestWithMethod:@"POST" URL:media parameters:@{@"media":imageString} error:&error];
[[[Twitter sharedInstance] APIClient] sendTwitterRequest:request completion:^(NSURLResponse *urlResponse, NSData *data, NSError *connectionError) {
NSError *jsonError;
NSDictionary *json = [NSJSONSerialization
JSONObjectWithData:data
options:0
error:&jsonError];
NSLog(@"Media ID : %@",[json objectForKey:@"media_id_string"]);
// Post tweet With media_id
}];
关于iOS - 无法使用 Twitter/Fabric New SDK 上传媒体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29555971/