我想将tinypng api集成到我的iOS应用程序中。但我在他们的网站上找不到关于如何编写objective-c代码或从curl命令转换上传文件进行处理的任何资料。卷曲api如下:
curl --user api:YOUR_API_KEY \ --data-binary @ unoptimized.png -i https://api.tinify.com/shrink
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方法上传图片有问题。
我该如何解决这个问题?