通缉:使用AFNetworking-2进行基本身份validation的JSON / POST的最新示例

我有一个玩具应用程序,使用基本身份validation安全提交https JSON / POST。 我被告知我应该考虑使用AFNetworking。 我已经能够安装AFNetwork-2到我的XCode项目(ios7目标,XCode5)就好了。 但是这里没有一个例子似乎与当前版本的AFNetworking-2相关,而是与之前的版本相关。 AFNetworking文档非常稀less,所以我正在努力拼凑。 非AFNetworking代码看起来像这样:

NSURL *url = [NSURL URLWithString:@"https://xxx.yyy.zzz.aaa:bbbbb/twig_monikers"]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy: NSURLRequestUseProtocolCachePolicy timeoutInterval: 10.0]; NSData *requestData = [NSJSONSerialization dataWithJSONObject: [self jsonDict] options: 0 error: nil]; [request setHTTPMethod: @"POST"]; [request setValue: @"application/json" forHTTPHeaderField: @"Accept"]; [request setValue: @"application/json" forHTTPHeaderField: @"Content-Type"]; [request setValue:[NSString stringWithFormat: @"%d", [requestData length]] forHTTPHeaderField: @"Content-Length"]; NSData *plainPassText = [@"app_pseudouser:sample_password" dataUsingEncoding:NSUTF8StringEncoding]; NSString *base64PassText = [plainPassText base64EncodedStringWithOptions: NSDataBase64Encoding76CharacterLineLength]; [request setValue:[NSString stringWithFormat: @"Basic %@", base64PassText] forHTTPHeaderField: @"Authorization"]; FailedCertificateDelegate *fcd=[[FailedCertificateDelegate alloc] init]; NSURLConnection *c=[[NSURLConnection alloc] initWithRequest:request delegate:fcd startImmediately:NO]; [c setDelegateQueue:[[NSOperationQueue alloc] init]]; [c start]; NSData *data=[fcd getData]; if (data) NSLog(@"Submit response data: %@", [NSString stringWithUTF8String:[data bytes]]); 

我不想找人为我写代码。 我似乎无法弄清楚如何映射AFNetworking-2部分。 任何链接,或例子,或解释非常欢迎。

更新1

以上是已知工作的非AF版本。 为了一气呵成,我试了一下:

 AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; manager.requestSerializer = [AFJSONRequestSerializer serializer]; [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"app_pseudouser" password:@"sample_password"]; AFHTTPRequestOperation *operation = [manager PUT: @"https://172.16.214.214:44321/twig_monikers" parameters: [self jsonDict] success:^(AFHTTPRequestOperation *operation, id responseObject){ NSLog(@"Submit response data: %@", responseObject);} failure:^(AFHTTPRequestOperation *operation, NSError *error){ NSLog(@"Error: %@", error);} ]; 

其中产生以下错误:

 2013-10-09 11:41:38.558 TwigTag[1403:60b] Error: Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn't be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x1662c1e0 {NSErrorFailingURLKey=https://172.16.214.214:44321/twig_monikers, NSErrorFailingURLStringKey=https://172.16.214.214:44321/twig_monikers} 

在服务器端看,没有任何东西能够通过。 我不知道是因为https,还是什么,但是我可以把应用程序翻回原来的代码,这样就好了。

更新:下面的JSON部分被发现用于PUT / POST,但不适用于GET / HEAD / DELETE

经过一番争吵和外面的帮助,我find了一些工作,我想作为纪念品离开。 最后,AFNetworking-2给我留下了非常深刻的印象。 这是如此简单,我一直在努力使它比应该更难。 给定一个返回json数据包发送的jsonDict方法,我创build了以下内容:

 - (void) submitAuthenticatedRest_PUT { // it all starts with a manager AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; // in my case, I'm in prototype mode, I own the network being used currently, // so I can use a self generated cert key, and the following line allows me to use that manager.securityPolicy.allowInvalidCertificates = YES; // Make sure we a JSON serialization policy, not sure what the default is manager.requestSerializer = [AFJSONRequestSerializer serializer]; // No matter the serializer, they all inherit a battery of header setting APIs // Here we do Basic Auth, never do this outside of HTTPS [manager.requestSerializer setAuthorizationHeaderFieldWithUsername:@"basic_auth_username" password:@"basic_auth_password"]; // Now we can just PUT it to our target URL (note the https). // This will return immediately, when the transaction has finished, // one of either the success or failure blocks will fire [manager PUT: @"https://101.202.303.404:5555/rest/path" parameters: [self jsonDict] success:^(AFHTTPRequestOperation *operation, id responseObject){ NSLog(@"Submit response data: %@", responseObject);} // success callback block failure:^(AFHTTPRequestOperation *operation, NSError *error){ NSLog(@"Error: %@", error);} // failure callback block ]; } 

3个安装语句,然后是2个消息发送,这确实很简单。

编辑/添加:这是一个@jsonDict实现的例子:

 - (NSMutableDictionary*) jsonDict { NSMutableDictionary *result = [[NSMutableDictionary alloc] init]; result[@"serial_id"] = self.serialID; result[@"latitude"] = [NSNumber numberWithDouble: self.location.latitude]; result[@"longitude"] = [NSNumber numberWithDouble: self.location.longitude]; result[@"name"] = self.name; if ([self hasPhoto]) { result[@"photo-jpeg"] = [UIImageJPEGRepresentation(self.photo, 0.5) base64EncodedStringWithOptions: NSDataBase64Encoding76CharacterLineLength]; } return result; 

}

它应该只是返回string的string和简单的对象作为值(NSNumber,NSString,NSArray(我认为)等)。 JSON编码器为您完成。