Open inb4ohnoes opened 8 years ago
I needed to support a self-signed cert, which was not trusted in the keychain. Since "NSURLConnection sendSynchronousRequest" does not support delegate.
So implemented this
- (NSString *)sartSynchronousSessionWithError:(NSError **)error
{
NSURLRequest *request = [self prepareURLRequest];
__block NSURLResponse *urlResponse = nil;
dispatch_semaphore_t sem;
__block NSData *result = nil;
__block NSError *blkErr = nil;
sem = dispatch_semaphore_create(0);
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:nil];
[[defaultSession dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *err)
{
if (err) {
blkErr = err;
}
urlResponse = response;
if (err == nil) {
result = data;
}
dispatch_semaphore_signal(sem);
}] resume];
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
// If Error, return error
if (blkErr) {
if (error != NULL) *error = blkErr;
return nil;
}
if (urlResponse)
{
if([urlResponse isKindOfClass:[NSHTTPURLResponse class]])
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)urlResponse;
self.responseHeaders = [httpResponse allHeaderFields];
self.responseStatus = [httpResponse statusCode];
self.responseStringEncodingName = [httpResponse textEncodingName];
}
}
self.responseString = [self stringWithData:result encodingName:_responseStringEncodingName];
self.responseData = [NSMutableData dataWithData:result];
if(self.responseStatus >= 400) {
if (error != NULL) *error = [self errorDescribingRequestNonfulfillment];
}
return _responseString;
}
I feel like this should be updated pretty soon...