簡単な裏話として、以前の開発者は ASIHTTPRequest を使用して POST リクエストを作成し、Web サービスからデータを取得しました。不明な理由により、アプリのこの部分が機能しなくなりました。将来の証明と AFNetworking を使用するのに十分な時間のように思えました。REST Web サービスは CakePHP フレームワークで実行されます。
つまり、AFNetworking を使用して要求応答文字列を受信していません。
curl を使用してデータを正常に投稿し、適切な応答を受け取ることができるため、Web サービスが機能していることはわかっています。 /api/class/function.plist
以前の開発者の指示に従って、次のことを思いつきました。
#import "AFHTTPRequestOperation.h"
…
- (IBAction)loginButtonPressed {
NSURL *url = [NSURL URLWithString:@"https://example.com/api/class/function.plist"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setValue:[usernameTextField text] forHTTPHeaderField:@"data[User][email]"];
[request setValue:[passwordTextField text] forHTTPHeaderField:@"data[User][password]"];
AFHTTPRequestOperation *operation = [[[AFHTTPRequestOperation alloc] initWithRequest:request] autorelease];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@"operation hasAcceptableStatusCode: %d", [operation.response statusCode]);
NSLog(@"response string: %@ ", operation.responseString);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"error: %@", operation.responseString);
}];
[operation start];
}
出力: 操作 hasAcceptableStatusCode: 200 応答文字列: 空の plist ファイル
試みられた解決策 1: AFNetworking Post Request 提案された解決策は、actionWithRequest と呼ばれる AFHTTPRequestOperation の関数を使用します。ただし、上記のソリューションを使用しようとすると、「クラス メソッド '+operationWithRequest:completion:' が見つかりません (戻り型のデフォルトは 'id' です]」という警告が表示されます。
試みられた解決策 2: NSURLConnection. 出力: 成功ログ メッセージは出力できますが、応答文字列は出力できません。*更新 - 空の plist を返します。
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
NSString *httpBodyData = @"data[User][email]=username@example.com&data[User][password]=awesomepassword";
[httpBodyData dataUsingEncoding:NSUTF8StringEncoding];
[req setHTTPMethod:@"POST"];
[req setHTTPBody:[NSData dataWithContentsOfFile:httpBodyData]];
NSHTTPURLResponse __autoreleasing *response;
NSError __autoreleasing *error;
[NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
// *update - returns blank plist
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"responseData %@",str);
if (error == nil && response.statusCode == 200) {
// Process response
NSLog(@"success");//returns success code of 200 but blank
NSLog(@"resp %@", response );
} else {
// Process error
NSLog(@"error");
}