简体   繁体   中英

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. I tested a dummy PUT request using https://www.hurl.it/ and it worked. 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. That, apparently, is very important to specify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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