.M файл. Здесь я аутентифицирую свой сертификат собственного знака и извлекаю его с помощью соединения nsurl и разбора в nsxmlparser перед помещая их в таблицу. Но я могу получить данные, но могу получить конкретный элемент с именем «Severity». Пожалуйста помоги.!! Мне нужно загрузить элементы в теге Severity в массив и вставить в представление таблицы.IOS Как получить один из элементов в xml после успешного вызова и поместить его в массив для отображения в tableview.
// IncidentTableViewController.m
#import "IncidentTableViewController.h"
#import "InviteViewController.h"
#import "Incidents.h"
#import "FeedListMenuView.h"
#import "FeedListMenuView.h"
#import "FeedViewController.h"
@interface IncidentTableViewController()
@property NSString *currentElement;
@property NSMutableData *webResponseData;
@property NSMutableDictionary *dictBook;
@property NSMutableArray *arrBook;
@property NSMutableString *elementValue;
@end
@interface FeedViewController()
@end
@implementation IncidentTableViewController
//@synthesize response;
//@synthesize status;
@synthesize resultLabel;
@synthesize webResponseData, currentElement;
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"Response recieved");
output= [[NSMutableArray alloc] init];
feeds = [[NSMutableArray alloc] init];
// NSString *severity = @"Informational";
NSString *soapMessage = @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
"<soap:Body>"
" <IncidentGetList xmlns=\"https://www.monitoredsecurity.com/\">"
"<Severity></Severity>"
"<SourceOrganization></SourceOrganization>"
"<DestinationOrganization></DestinationOrganization>"
"<MaxIncidents></MaxIncidents>"
"<SourceIP></SourceIP>"
"<Category></Category>"
"<ExcludeCategory></ExcludeCategory>"
"<StartTimeStampGMT></StartTimeStampGMT>"
"<EndTimeStampGMT></EndTimeStampGMT>"
"<CustomerSeverity></CustomerSeverity>"
"</IncidentGetList>"
"</soap:Body>"
"</soap:Envelope>";
NSURL *url = [NSURL URLWithString:@"https://api.monitoredsecurity.com/SWS/incidents.asmx"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[theRequest addValue: @"https://www.monitoredsecurity.com/IncidentGetList" forHTTPHeaderField:@"SOAPAction"];
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
[connection start];
if(connection)
{
webResponseData = [NSMutableData data] ;
}
else
{
NSLog(@"Connection is NULL");
}
// Menu View
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
// Insert Navigation Bar
// [self insertNavBarWithScreenName:SCREEN_INCIDENT];
//
// CGRect frm = btnDownArrow.frame;
// frm.origin.x = 185;
// frm.origin.y = 42;
// [btnDownArrow setFrame:frm];
// [self.navBarView addSubview:btnDownArrow];
//
//
//
// [self addGestureRecognizersToPiece:self.view];
}
- (void)addGestureRecognizersToPiece:(UIView *)piece
{
UITapGestureRecognizer * tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapPiece:)];
tapGesture.delegate = self;
[piece addGestureRecognizer:tapGesture];
}
- (void) tapPiece:(UITapGestureRecognizer *)gestureRecognizer {
[btnDownArrow setSelected:NO];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
//
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//#warning Incomplete implementation, return the number of sections
// return 1;
//}
//
//- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//#warning Incomplete implementation, return the number of rows
// return [output countc];
//}
#pragma mark --
#pragma mark -- Set navigationBar --
- (void) didClickNavBarLeftButton
{
CGRect frm = self.view.frame;
frm.origin.x = 254;
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3f];
[UIView setAnimationDelegate:self];
[self.view setFrame:frm];
//[self setEnable:NO];
[UIView commitAnimations];
[self tapPiece:nil];
}
- (void) didClickNavBarRightButton
{
[self tapPiece:nil];
if (rightController == nil) {
rightController = [[InviteViewController alloc] viewFromStoryboard];
[self.view.superview addSubview:rightController.view];
[rightController.view setFrame:CGRectMake(320, 0, gScreenSize.width, gScreenSize.height)];
}
[collectView setUserInteractionEnabled:!(self.view.frame.origin.x > -254)];
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.3f];
[UIView setAnimationDelegate:self];
if (self.view.frame.origin.x > -254) {
self.view.transform = CGAffineTransformMakeTranslation(-254 * 2, 0);
rightController.view.transform = CGAffineTransformMakeTranslation(-254, 0);
}
else {
self.view.transform = CGAffineTransformMakeTranslation(-254, 0);
rightController.view.transform = CGAffineTransformMakeTranslation(0, 0);
}
[UIView commitAnimations];
}
#pragma mark --
#pragma mark -- UICollectionViewDataSource, UICollectionViewDelegate --
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [[arrFeeds objectAtIndex:section] count];
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return [arrFeeds count];
}
#pragma mark --
#pragma mark -- FeedListMenuViewDelegate --
- (void) didClickFeedListMenu:(FeedListMenuView *)flmv index:(int)index
{
[btnDownArrow setSelected:NO];
}
- (void)connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"Response recieved");
[self.webResponseData setLength:0];
}
- (void)connection:(NSURLConnection*) connection didReceiveData:(NSData *)data
{
NSLog(@"Data recieved");
// NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[self.webResponseData appendData:data];
// NSLog(responseString);
// [response setText:responseString];
//[status setText:@"Response retrieved async"];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"Received %lu Bytes", (unsigned long)[webResponseData length]);
NSString *theXML = [[NSString alloc] initWithBytes:
[webResponseData mutableBytes] length:[webResponseData length] encoding:NSUTF8StringEncoding];
NSLog(@"%@",theXML);
//now parsing the xml
NSData *myData = [theXML dataUsingEncoding:NSUTF8StringEncoding];
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:myData];
//setting delegate of XML parser to self
xmlParser.delegate = self;
[xmlParser parse];
// Run the parser
@try{
BOOL parsingResult = [xmlParser parse];
NSLog(@"parsing result = %hhd",parsingResult);
}
@catch (NSException* exception)
{
UIAlertView* alert = [[UIAlertView alloc]initWithTitle:@"Server Error" message:[exception reason] delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[alert show];
return;
}
}
//Implement the NSXmlParserDelegate methods
-(void) parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:
(NSString *)qName attributes:(NSDictionary *)attributeDict
{
element = elementName;
if ([element isEqualToString:@"SecurityIncidentSummary"]) {
IncidentGetList = [[NSMutableDictionary alloc] init];
Severity = [[NSMutableString alloc] init];
} //NSLog(@"current element: ", elementName);
}
- (void)parserDidStartDocument:(NSXMLParser *)parser{
NSLog(@"File found and parsing started");
}
- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
if ([element isEqualToString:@"Severity"]) {
[Severity appendString:string];
}
}
- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"SecurityIncidentSummary"]) {
[IncidentGetList setObject:Severity forKey:@"Severity"];
[feeds addObject:[IncidentGetList copy]];
}
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSLog(@"Final Feed : %@",feeds);
}
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace {
return [protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust];
}
- (void)connection:(NSURLConnection *)connection
willSendRequestForAuthenticationChallenge:
(NSURLAuthenticationChallenge *)challenge
{
if ([challenge previousFailureCount] == 0)
{
SecIdentityRef identity = [self getClientCertificate];
CFArrayRef certs = [self getCertificate];
NSArray *myArray = (__bridge NSArray *)certs;
NSURLCredential *newCredential = [NSURLCredential credentialWithIdentity:identity
certificates:myArray persistence:NSURLCredentialPersistenceNone];
[challenge.sender useCredential:newCredential forAuthenticationChallenge:challenge];
}
else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
-(CFArrayRef)getCertificate
{
SecIdentityRef identity = [self getClientCertificate];
SecCertificateRef certificate = nil;
SecIdentityCopyCertificate(identity, &certificate);
SecCertificateRef certs[1] = {certificate};
CFArrayRef array = CFArrayCreate(NULL, (const void **) certs, 1, NULL);
SecPolicyRef myPolicy = SecPolicyCreateBasicX509();
SecTrustRef myTrust;
OSStatus status = SecTrustCreateWithCertificates(array, myPolicy, &myTrust);
if (status == noErr){
NSLog(@"No Err creating certificate");
}
else{
NSLog(@"Possible Err Creating certificate");
}
return array;
}
-(SecIdentityRef)getClientCertificate
{
SecIdentityRef identityApp = nil;
NSString *thePath = [[NSBundle mainBundle] pathForResource:@"cert" ofType:@"p12"];
NSData *PKCS12Data = [[NSData alloc] initWithContentsOfFile:thePath];
CFDataRef inPKCS12Data = (__bridge CFDataRef)PKCS12Data;
CFStringRef password = CFSTR("123456");
const void *keys[] = {kSecImportExportPassphrase}; //kSecImportExportPassphrase };
const void *values[] = {password};
CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
OSStatus securityError = SecPKCS12Import(inPKCS12Data, options, &items);
CFRelease(options);
CFRelease(password);
if (securityError == errSecSuccess)
{
NSLog(@"Success opening p12 certificate. Items: %ld", CFArrayGetCount(items));
CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
identityApp = (SecIdentityRef)CFDictionaryGetValue(identityDict,
kSecImportItemIdentity);
}
else{
NSLog(@"Error opening Certificate.");
}
return identityApp;
}
//- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
// NSError *error = nil;
// NSString *path = [[NSBundle mainBundle] pathForResource:[@"SII_2350" stringByDeletingPathExtension] ofType:[@"p12" pathExtension]];
// NSData *certData = [[NSData alloc] initWithContentsOfFile:path options:0 error:&error];
// CFDataRef inP12data = (__bridge CFDataRef)certData;
// SecIdentityRef identity;
// SecTrustRef trust;
//
//
// OSStatus status = extractIdentityAndTrust(inP12data, &identity, &trust);
// NSLog(@"status %d", (int)status);
// if(status == errSecSuccess) {
// SecCertificateRef certificate;
// SecIdentityCopyCertificate(identity, &certificate);
// const void *certs[] = { certificate };
// CFArrayRef certsArray = CFArrayCreate(NULL, certs, 1, NULL);
// NSArray *certificatesForCredential = (__bridge NSArray *)certsArray;
// NSURLCredential *credential = [NSURLCredential credentialWithIdentity:identity
// certificates:certificatesForCredential
// persistence:NSURLCredentialPersistencePermanent];
// [challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
// CFRelease(identity);
// CFRelease(certificate);
// CFRelease(certsArray);
// }
// else {
// [challenge.sender cancelAuthenticationChallenge:challenge];
// }
//
//
//}
- (void)connection:(NSURLConnection*) connection didFailWithError:(NSError *)error
{
NSLog([NSString stringWithFormat:@"Did recieve error: %@", [error localizedDescription]]);
NSLog([NSString stringWithFormat:@"%@", [error userInfo]]);
}
OSStatus extractIdentityAndTrust(CFDataRef inPKCS12Data, SecIdentityRef *identity, SecTrustRef *trust){
// OSStatus securityError = errSecSuccess;
//
// CFStringRef password = CFSTR("123456");
// const void *keys[] = { kSecImportExportPassphrase };
// const void *values[] = { password };
//
// CFDictionaryRef options = CFDictionaryCreate(NULL, keys, values, 1, NULL, NULL);
//
// CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
// securityError = SecPKCS12Import(inP12data, options, &items);
//
// if (securityError == 0) {
// CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex(items, 0);
// const void *tempIdentity = NULL;
// tempIdentity = CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemIdentity);
// *identity = (SecIdentityRef)tempIdentity;
// const void *tempTrust = NULL;
// tempTrust = CFDictionaryGetValue(myIdentityAndTrust, kSecImportItemTrust);
// *trust = (SecTrustRef)tempTrust;
// }
//
// if (options) {
// CFRelease(options);
// }
//
// return securityError;
OSStatus securityError = errSecSuccess;
CFStringRef password = CFSTR("123456");
const void *keys[] = { kSecImportExportPassphrase };
const void *values[] = { password };
CFDictionaryRef optionsDictionary = CFDictionaryCreate(
NULL, keys,
values, 1,
NULL, NULL);
CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
securityError = SecPKCS12Import(inPKCS12Data,
optionsDictionary,
&items);
if (securityError == 0) {
CFDictionaryRef myIdentityAndTrust = CFArrayGetValueAtIndex (items, 0);
const void *tempIdentity = NULL;
tempIdentity = CFDictionaryGetValue (myIdentityAndTrust,
kSecImportItemIdentity);
*identity = (SecIdentityRef)tempIdentity;
const void *tempTrust = NULL;
tempTrust = CFDictionaryGetValue (myIdentityAndTrust, kSecImportItemTrust);
*trust = (SecTrustRef)tempTrust;
}
if (optionsDictionary) {
CFRelease(optionsDictionary);
}
return securityError;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
return [feeds count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = @"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
if(cell == nil){
cell= [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
}
cell.textLabel.text= [[feeds objectAtIndex:indexPath.row]objectForKey:@"Severity"];
return cell;
}
//UNTIL HERE
//
//- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//// UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:<#@"reuseIdentifier"#> forIndexPath:indexPath];
// static NSString *cellIdentifier = @"cell";
//
// UITableView *cell = [tableView dequeueReusableCellWithIdentifier:[cellIdentifier ];
//
// if(cell == nill){
// cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]autorelease];
//
// }
//
//
////
//// return cell;
//}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/
/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the row from the data source
[tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
#pragma mark - Table view delegate
//In a xib-based application, navigation from a table can be handled in -tableView:didSelectRowAtIndexPath:
//- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
// // Navigation logic may go here, for example:
// // Create the next view controller.
// // <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:<#@"Nib name"#> bundle:nil];
//
// // Pass the selected object to the new view controller.
//
// // Push the view controller.
// //[self.navigationController pushViewController:detailViewController animated:YES];
// [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
//
//}
/*
#pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
@end
.h файл
#import <UIKit/UIKit.h>
#import "CustomNavViewController.h"
#import "FeedListMenuView.h"
#import <UIKit/UIKit.h>
#import <Security/Security.h>
#import <CoreFoundation/CoreFoundation.h>
#import "SYSoapTool.h"
@interface IncidentTableViewController :UIViewController< UITableViewDataSource,UITableViewDelegate, UIGestureRecognizerDelegate, SOAPToolDelegate, NSXMLParserDelegate> {
IBOutlet UIButton * btnDownArrow;
IBOutlet UICollectionView * collectView;
NSMutableArray * arrFeeds;
SuperViewController * rightController;
NSMutableArray *output;
BOOL errorParsing;
NSMutableString *strCaptured;
NSMutableDictionary *item;
}
@property (weak, nonatomic) IBOutlet UITableView *datalist;
@property (weak, nonatomic) IBOutlet UILabel *resultLabel;
@property(nonatomic, retain) IBOutlet UILabel *status;
@property(nonatomic, retain) IBOutlet UITextView *response;
-(IBAction)retrieveResponseAsync:(id)sender;
- (void)connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *) connection didReceiveData:(NSData *)data;
- (void)connection:(NSURLConnection *) connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
- (void)connection:(NSURLConnection *) connection didFailWithError:(NSError *)error;
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace;
OSStatus extractIdentityAndTrust(CFDataRef inP12data, SecIdentityRef *identity, SecTrustRef *trust);
@end
Можете ли вы ответить на мои базы кодов, но не показывал мне свои коды и ожидать, что я понимаю ваши коды. потому что я тоже не мог понять. вот почему я спрашиваю здесь. Спасибо большое! – zac
Я редактирую свой метод для вашего Xml Parser, а также не заходил на фид в режиме просмотра. Feeddddd = [[NSMutableArray alloc] init]; – vp2698
Где вы объявили атрибут элемента? – zac