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

前面咱们完成了能够发布一条纯文字的微博,如今来经过从相册中获取到的图片,而后发一个带有图片的微博。json

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

###请求参数并发

输入图片说明

###文件上传的参数pic不能和普通的字符串参数混在一块儿,须要用不一样的方法分开处理。app

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

// 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, 发送带有一张图片的微博完美实现^_^code

输入图片说明

相关文章
相关标签/搜索