简体   繁体   English

如何在iOS中对包含图片(nsdata)的URL发出PUT请求

[英]How do I make a PUT request to a URL with an image (nsdata) in iOS

I've been scratching my head for hours. 我已经挠头好几个小时了。 I keep getting connection time outs on my completion handler. 我不断在完成处理程序上获得连接超时。 This seems like it should be easy... 这似乎应该很容易...

Can anyone help please? 有人可以帮忙吗?

NSMutableURLRequest *uploadRequest = [[NSMutableURLRequest alloc] init];
[uploadRequest setURL:[NSURL URLWithString:PUTURL]];
uploadRequest.cachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
[uploadRequest setHTTPMethod:@"PUT"];
[uploadRequest setHTTPBody:imageDataToUpload];
[uploadRequest setValue:[NSString stringWithFormat:@"%lu", (unsigned long)[self.assetDataToUpload length]] forHTTPHeaderField:@"Content-Length"];
[uploadRequest setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];

NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:uploadRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                        NSLog(@"YAY COMPLETED");
                        self.didUpload = true;
                        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                    }];
[dataTask resume];

Also, I should mention that my PUTURL is a presignedurl generated from s3. 另外,我应该提到我的PUTURL是从s3生成的presignedurl。 I tested a dummy PUT request using https://www.hurl.it/ and it worked. 我使用https://www.hurl.it/测试了一个虚拟的PUT请求,该请求有效。 So it seems to indicate that it's a problem with my code. 因此,似乎表明我的代码有问题。

Finally figured it out! 终于想通了! There's nothing wrong with this code. 这段代码没有错。 On my server side where I acquired the presignedurl, I forgot to include the ContentType. 在获取presignedurl的服务器端,我忘记包含ContentType。 That, apparently, is very important to specify. 显然,这很重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM