从远程XML iOS获取数据

时间:2013-11-07 13:10:21

标签: ios objective-c xml-parsing

在我的应用程序中,我需要连接到服务器以读取aml信息。要访问此服务器,当我使用普通浏览器时,它要求我插入用户名和密码。 我如何访问这些信息? 我试着使用这段代码:

#import "XmlCategoryReader.h"

@interface XmlCategoryReader() {
    NSXMLParser *categoryParser;
}

@end

@implementation XmlCategoryReader

// Inizializzazione dell'array che conterrà i dati scaricati da internet
- (id)init {
    self = [super self];
    if (self) {
        self.categoryArray = [[NSMutableArray alloc]init];
    }
    return self;
}

// Metodo che effettua la connessione per recuperare le informazioni dall'xml remoto
- (void)parseXML {
    NSString *stringUrl = [NSString stringWithFormat:@"http://54.204.6.246/magento8/api/rest/products/?category_id=3"];
    NSURL *url = [NSURL URLWithString:stringUrl];
    NSString *host = [url host];
    if (url == nil || host == nil) {
        NSData *data = [[NSData alloc]initWithContentsOfURL:url];
        categoryParser = [[NSXMLParser alloc]initWithData:data];
    } else {
        categoryParser = [[NSXMLParser alloc]initWithContentsOfURL:url];
    }
    [categoryParser setDelegate:self];
    [categoryParser setShouldProcessNamespaces:NO];
    [categoryParser setShouldReportNamespacePrefixes:NO];
    [categoryParser setShouldResolveExternalEntities:NO];
    [categoryParser parse];
}

- (void)parserDidStartDocument:(NSXMLParser *)parser {
    NSLog(@"Documento trovato, inizio il parsing");
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError {
    NSLog(@"Errore Parsing: %@", parseError);
}

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict {

}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {
}

- (void)parserDidEndDocument:(NSXMLParser *)parser {
}

@end

但是当我尝试在模拟器上运行应用程序时,它会返回给我:

Error Domain=NSXMLParserErrorDomain Code=65 "The operation couldn’t be completed. (NSXMLParserErrorDomain error 65.)" UserInfo=0x8b5a870 {NSXMLParserErrorLineNumber=1, NSXMLParserErrorColumn=47, NSXMLParserErrorMessage=Space required after the Public Identifier
}

我做错了什么? 你能救我吗?

1 个答案:

答案 0 :(得分:0)

您需要实现此方法:

-(void)connection:(NSURLConnection *)connection didCancelAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if([challenge previousFailureCount] == 0) {

    NSURLCredential *newCredential =[NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistenceForSession];

    [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];

}
else {
    NSLog(@"previous authentication failure");
 }
}