• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

ios - 如何在 Imgur 用户线上发布图片

[复制链接]
菜鸟教程小白 发表于 2022-12-12 10:41:07 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我在应该允许在用户墙上发布图像的应用程序下工作。 一开始他正在获得授权,在这个阶段一切都很好。但是,当我尝试发出发布请求时 - 没有发布任何内容。你能帮忙解决下一个问题吗? 当用户选择图像并按下发布按钮时:

- (void) postActionSelected
{

    NSString *title = [[self titleTextField] text];
    NSString *description = [[self commentTextField] text];

    NSData *imageData = UIImageJPEGRepresentation(self.currentImage.image, 0.5);
    [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{



    [imgurServerManager uploadPhoto:imageData
                           title:title
                     description:description
                 completionBlock:^(NSString *result) {
                     dispatch_async(dispatch_get_main_queue(), ^{
                         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                     });
                 } failureBlock:^(NSURLResponse *response, NSError *error, NSInteger status) {
                     dispatch_async(dispatch_get_main_queue(), ^{
                         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
                         [[[UIAlertView alloc] initWithTitle"Upload Failed"
                                                     message:[NSString stringWithFormat"%@ (Status code %ld)", [error localizedDescription], (long)status]
                                                    delegate:nil
                                           cancelButtonTitle:nil
                                           otherButtonTitles"OK", nil] show];
                     });
                 }];

});

}

然后在 ImGurServerManager 这个帖子应该完成:

+ (void)uploadPhotoNSData*)imageData
              titleNSString*)title
        descriptionNSString*)description
    completionBlockvoid(^)(NSString* result))completion
       failureBlockvoid(^)(NSURLResponse *response, NSError *error, NSInteger status))failureBlock
{
    NSAssert(imageData, @"Image data is required");
    //NSAssert(access_token, @"Access token is required");

    NSString *urlString = @"https://api.imgur.com/3/upload";
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod"OST"];

    NSMutableData *requestBody = [[NSMutableData alloc] init];

    NSString *boundary = @"---------------------------0983745982375409872438752038475287";

    NSString *contentType = [NSString stringWithFormat"multipart/form-data; boundary=%@", boundary];
    [request addValue:contentType forHTTPHeaderField"Content-Type"];

    //[request addValue:[NSString stringWithFormat"access_token %@", access_token] forHTTPHeaderField"access_token"];

    [requestBody appendData:[[NSString stringWithFormat"--%@\r\n", boundary]
          dataUsingEncoding:NSUTF8StringEncoding]];
    [requestBody appendData:[@"Content-Disposition: attachment; name=\"image\"; filename=\".tiff\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];

    [requestBody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [requestBody appendData:[NSData dataWithData:imageData]];
    [requestBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];


    if (title) {
        [requestBody appendData:[[NSString stringWithFormat"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [requestBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"title\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [requestBody appendData:[title dataUsingEncoding:NSUTF8StringEncoding]];
        [requestBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }


    if (description) {
        [requestBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
        [requestBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"description\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
        [requestBody appendData:[description dataUsingEncoding:NSUTF8StringEncoding]];
        [requestBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    }

    [requestBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] 
          dataUsingEncoding:NSUTF8StringEncoding]];

    [request setHTTPBody:requestBody];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
        NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if ([responseDictionary valueForKeyPath:@"data.error"]) {
            if (failureBlock) {
                if (!error) {

                    error = [NSError errorWithDomain:@"imguruploader" code:10000 userInfo:@{NSLocalizedFailureReasonErrorKey : [responseDictionary valueForKeyPath:@"data.error"]}];
                }
                failureBlock(response, error, [[responseDictionary valueForKey:@"status"] intValue]);
            }
        } else {
            if (completion) {
                completion([responseDictionary valueForKeyPath:@"data.link"]);
            }

        }

    }];
}

我想这里的原因是我错过了一些额外的参数,但我完全迷失了它。 提前谢谢你。



Best Answer-推荐答案


https://api.imgur.com/endpoints/image您看到您需要使用以下参数执行帖子(请参阅:ios Upload Image and Text using HTTP POST):

我认为您缺少 _params[@"type"] = @"base64";

// Dictionary that holds post parameters. You can set your post parameters that your server accepts or programmed to accept.
NSMutableDictionary* _params = [[NSMutableDictionary alloc] init];
_params[@"type"] = @"base64";
_params[@"name"] = @"myImage";

// the boundary string : a random string, that will not repeat in post data, to separate post data fields.
NSString *BoundaryConstant = [NSString stringWithString:@"----------V2ymHFg03ehbqgZCaKO6jy"];

// create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];                                    
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"OST"];

// set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", BoundaryConstant];
[request setValue:contentType forHTTPHeaderField: @"Content-Type"];

// post body
NSMutableData *body = [NSMutableData data];

// add params (all params are strings)
for (NSString *param in _params) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", param] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [_params objectForKey:param]] dataUsingEncoding:NSUTF8StringEncoding]];
}

// add image data
NSData *imageData = UIImageJPEGRepresentation(imageToPost, 1.0);
if (imageData) {
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", FileParamConstant] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: image/jpeg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", BoundaryConstant] dataUsingEncoding:NSUTF8StringEncoding]];

// setting the body of the post to the reqeust
[request setHTTPBody:body];

// set the content-length
NSString *postLength = [NSString stringWithFormat:@"%d", [body length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];

// set URL
[request setURL:requestURL];

关于ios - 如何在 Imgur 用户线上发布图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35626770/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap