AFNetworking を使用して JSON を投稿しようとしています。
使用しているコードは次のとおりです。
+ (RESTAPI *)sharedClient
{
static RESTAPI *_sharedClient = nil;
static dispatch_once_t oncePredicate;
dispatch_once(&oncePredicate, ^{
_sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:@"https://mybaseurl.com"]];
});
return _sharedClient;
}
- (id)initWithBaseURL:(NSURL *)url
{
self = [super initWithBaseURL:url];
if (!self) {
return nil;
}
[self setParameterEncoding:AFJSONParameterEncoding];
[self registerHTTPOperationClass:[AFJSONRequestOperation class]];
[self setDefaultHeader:@"Accept" value:@"application/json"];
[self setAllowsInvalidSSLCertificate:YES];
return self;
}
次のコードは機能しません。試行するたびに、次のエラーが表示されます。
操作を完了できませんでした。(NSURLErrorDomain エラー -1012。)
// this code does not works
//
- (void)loginNOTWORKING
{
RESTAPI *client = [RESTAPI sharedClient];
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
[[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];
NSDictionary *parameter = @{@"tgout": @"1",
@"tgin": @2,
@"username": @"foo",
@"password":@"bar"};
NSURLRequest *request = [client requestWithMethod:@"POST" path:@"/login" parameters:parameter];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
// code for successful return goes here
[[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
NSLog(@"THIS IS NEVER CALLED: %@", JSON);
// do something with return data
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
// code for failed request goes here
[[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
NSLog(@"SAD, VERY SAD: %@", error.localizedDescription);
// do something on failure
}];
[operation start];
}
このコードは機能します:
// this code WORKS
- (void)loginWORKING
{
RESTAPI *client = [RESTAPI sharedClient];
[[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
[[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];
NSDictionary *parameter = @{@"tgout": @"1",
@"tgin": @2,
@"username": @"foo",
@"password":@"bar"};
[client postPath:@"/login" parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
// Print the response body in text
NSLog(@"IT WORKS: %@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Response: %@", error.localizedDescription);
}];
}
最初のログイン方法が機能しないのはなぜですか? 私は何を間違っていますか?