如何将tinypng压缩图像api转换为目标c

时间:2016-05-31 02:18:12

标签: ios objective-c image curl

我想将tinypng api集成到我的iOS应用程序中。但我在他们的网站上找不到关于如何编写objective-c代码或从curl命令转换上传文件进行处理的任何资料。卷曲api如下:

curl --user api:YOUR_API_KEY \      --data-binary @ unoptimized.png -i https://api.tinify.com/shrink

我曾尝试为其编写http post代码,

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:TINY_PNG_HOST]
                                                       cachePolicy:NSURLRequestReloadIgnoringCacheData
                                                   timeoutInterval:8.f];
request.HTTPMethod = @"POST";

NSString *base64encodedKey = [[[NSString stringWithFormat:@"api:%@", apiKey] dataUsingEncoding:NSUTF8StringEncoding] base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
NSString *auth = [NSString stringWithFormat:@"Basic %@", base64encodedKey];

[request setValue:auth forHTTPHeaderField:@"Authorization"];

NSData *imageData = UIImageJPEGRepresentation(obj.imageIcon, 1);

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

NSMutableData *body = [NSMutableData data];
[body appendData:[[NSString stringWithFormat:@"rn--%@rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"wigi_item_image\";filename=\"item.jpg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Transfer-Encoding: binary\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[NSData dataWithData:imageData]];
[body appendData:[[NSString stringWithFormat:@"rn--%@--rn",boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: self delegateQueue: [NSOperationQueue mainQueue]];

NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithRequest:request];
[dataTask resume];

但总是失败的结果。我认为通过setHTTPBody方法上传图片有问题。

我该如何解决这个问题?

0 个答案:

没有答案