APIで機能する単純なGETリクエストを取得しようとしています。しかし、それはうまくいかないようで、理由はわかりません。
私のコードは次のとおりです
編集、NSURLCredentialも試しましたが、それも機能していないようです
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
NSString *urlAsString = @"https://www.test.com/api/v1/user/logout/";
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url]; [urlRequest setTimeoutInterval:30.0f];
[urlRequest setHTTPMethod:@"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response,NSData *data, NSError *error) {
if ([data length] >0 && error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"HTML = %@", html); }
else if ([data length] == 0 && error == nil){
NSLog(@"Nothing was downloaded."); }
else if (error != nil){
NSLog(@"Error happened = %@", error); }
}];
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
[challenge.sender useCredential:[NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust] forAuthenticationChallenge:challenge];
[challenge.sender continueWithoutCredentialForAuthenticationChallenge:challenge];
}
私のAPIはjsonを吐き出します。だから私は言うjsonオブジェクトを取り戻す必要があります
success: False
reason: 'Already Logged out'
しかし、代わりに次のエラーが発生します
2013-03-07 16:24:44.038 test[8957:1d03] Error happened = Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x715db20 {NSErrorFailingURLKey=https://www.test.com/api/v1/user/logout/, NSErrorFailingURLStringKey=https://www.test.com/api/v1/user/logout/, NSUnderlyingError=0x7181cb0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)"}
方法2
いくつかの調査の後、getリクエストを送信する別の方法を見つけましたが、この方法は問題なく機能しているようです。
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:@"https://www.test.com/api/v1/user/logout/"];
NSString *json = [NSString stringWithContentsOfURL:url
encoding:NSASCIIStringEncoding
error:&error];
if(!error) {
NSData *jsonData = [json dataUsingEncoding:NSASCIIStringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData
options:kNilOptions
error:&error];
BOOL success = [[jsonDict objectForKey:@"success"] boolValue];
if (!success) {
NSString *reason = [jsonDict objectForKey:@"reason"];
NSLog(@"Cannot log out, as user %@", reason);
}
//NSLog(@"JSON: %@", jsonDict);
}else{
NSLog(@"\nJSON: %@ \n Error: %@", json, error);
}
});