您的位置:首页 > 移动开发 > IOS开发

IOS博客项目搭建-17-发微博-发一张图片

2016-05-28 00:00 344 查看
前面我们完成了可以发布一条纯文字的微博,现在来通过从相册中获取到的图片,然后发一个带有图片的微博。

关于发送微博的接口,可以查询新浪的开放平台微博API接口文档,我们找到上传图片并发布一条新微博的接口,https://upload.api.weibo.com/2/statuses/upload.json

###请求参数



###文件上传的参数pic不能和普通的字符串参数混在一起,需要用不同的方法分开处理。

旧的将文件和普通参数写在一起的方法(经测试,该方法不能发送图片)

// 2.封装请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];

// 发送内容
params[@"status"] = self.textView.text;

// 根据之前封装的账号工具类IWAccountTool,登陆授权的账号信息被保存在本地,然后通过账号属性获取access_token
params[@"access_token"] = [IWAccountTool account].access_token;

// 上传图片(是否压缩,压缩质量为0.6,原图为1.0)
params[@"pic"] = UIImageJPEGRepresentation(self.imageView.image, 0.6);

// 3.发送请求
[mgr POST:@"https://upload.api.weibo.com/2/statuses/upload.json" parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[MBProgressHUD showSuccess:@"恭喜,发送成功"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 隐藏提醒框
[MBProgressHUD showError:@"抱歉,发送失败"];
}];

将文件和普通参数分开写的方法

/**
*  发有图片微博
*/
- (void)sendWithImage
{
// AFNetworking\AFN
// 1.创建请求管理对象
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

// 2.封装请求参数
NSMutableDictionary *params = [NSMutableDictionary dictionary];

// 发送内容
params[@"status"] = self.textView.text;

// 根据之前封装的账号工具类IWAccountTool,登陆授权的账号信息被保存在本地,然后通过账号属性获取access_token
params[@"access_token"] = [IWAccountTool account].access_token;

// 上传图片(是否压缩,压缩质量为0.6,原图为1.0)
// params[@"pic"] = UIImageJPEGRepresentation(self.imageView.image, 0.6);

// 3.发送请求
/*
[mgr POST:@"https://upload.api.weibo.com/2/statuses/upload.json" parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[MBProgressHUD showSuccess:@"恭喜,发送成功"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 隐藏提醒框
[MBProgressHUD showError:@"抱歉,发送失败"];
}];
*/
[mgr POST:@"https://upload.api.weibo.com/2/statuses/upload.json" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) { // 在发送请求之前调用这个block

//必须在这里说明需要上传哪些文件
NSData *data = UIImageJPEGRepresentation(self.imageView.image, 0.6);
[formData appendPartWithFileData:data name:@"pic" fileName:@"text.jpg" mimeType:@"image/jpeg"];

}  success:^(AFHTTPRequestOperation *operation, id responseObject) {
[MBProgressHUD showSuccess:@"恭喜,发送成功"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// 隐藏提醒框
[MBProgressHUD showError:@"抱歉,发送失败"];
}];

// 4.关闭控制器。当用户点击发送微博按钮后,需要将发微博界面关掉,因为发微博有时可能需要很长时间
[self dismissViewControllerAnimated:YES completion:nil];

}

OK, 发送带有一张图片的微博完美实现^_^

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息