【发布时间】:2014-05-18 12:46:52
【问题描述】:
您好,我正在开发一个新闻 iOS 应用程序,我正在从 XML 获取标题和描述,但我无法从 XML 获取图像,谁能帮我解决这个问题。
注意:我是这个 iOS 开发的新手,请帮我解决这个问题。提前致谢。
这是我的代码。
在 NewsViewController.h 中
#import <UIKit/UIKit.h>
@interface NewsViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,NSXMLParserDelegate>
@property (strong,nonatomic)IBOutlet UITableView *tblNews;
@property (strong,nonatomic)IBOutlet NSMutableArray *arrTitles;
@property (strong,nonatomic)IBOutlet NSMutableArray *arrDescription;
@property (strong,nonatomic)IBOutlet NSMutableArray *arrImages;
@property (strong,nonatomic)IBOutlet NSMutableArray *arrDate;
@end
在 NewsViewController.m 中
#import "NewsViewController.h"
#import "NewsTableViewCell.h"
#import "NewDetailsViewController.h"
@interface NewsViewController ()
{
NSString *temString;
NSMutableString *strTemp;
}
@end
@implementation NewsViewController
@synthesize arrImages;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
#pragma mark - View Life Cycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.arrTitles =[[NSMutableArray alloc] init];
self.arrDescription=[[NSMutableArray alloc]init];
self.arrImages=[[NSMutableArray alloc]init];
self.arrDate=[[NSMutableArray alloc]init];
[self makeRequestForNews];
// Do any additional setup after loading the view.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - make request for news
-(void)makeRequestForNews//http://www.shura.bh/MediaCenter/News/ExportNewsAsXml.aspx?Section=%D8%A3%D8%AE%D8%A8%D8%A7%D8%B1%20%D8%A7%D9%84%D9%85%D8%AC%D9%84%D8%B3
{
NSURL *url =[NSURL URLWithString:@"http://www.shura.bh/MediaCenter/News/ExportNewsAsXml.aspx?Section=%D8%A3%D8%AE%D8%A8%D8%A7%D8%B1%20%D8%A7%D9%84%D9%85%D8%AC%D9%84%D8%B3&RetrieveImageUrl=true"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//After making request the apparent thing is expecting the response that may be expected response or an Error. so create those objects and intialize them with NULL.
NSURLResponse *response = NULL;
NSError *requestError =NULL;
//Once you have response with you , Capture YOur Responce data using NsData.
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
//Convert the respnse Data into Response String.
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//Now We can start parsing the Data using XMl parser . you need XML parser in-order to use the below class method "dictionaryFOrXMLString".
NSError *parserError = NULL;
//XML parsing
NSXMLParser *xmlParser = [[NSXMLParser alloc] initWithData:responseData];
[xmlParser setDelegate:self];
[xmlParser parse];
//NSDictionary *xmlDict = [XMLReader dictionaryForXMLString:responseString error:NULL];
//once you have xmlDict handy, you can pass this to the any ViewController (Like table view) to populate the Data.
}
- (void)parserDidEndDocument:(NSXMLParser *)parser {
NSURL *imageURL = [NSURL URLWithString:[arrImages objectAtIndex:0]];
NSData *imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage *image = [UIImage imageWithData:imageData];
}
-(void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
if ([elementName isEqualToString:@"ShuraNews"])
{
}
if ([elementName isEqualToString:@"PUBLISHINGPAGEIMAGE"])
{
NSLog(@"dict === %@",attributeDict);
}
strTemp=[NSMutableString new];
}
-(void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
//temString =string;
[strTemp appendString:string];
}
-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
if ([elementName isEqualToString:@"TITLE"])
{
NSLog(@"temstring=== %@", strTemp);
[self.arrTitles addObject:strTemp];
}
if ([elementName isEqualToString:@"PUBLISHINGPAGECONTENT"])
{
NSLog(@"temstring=== %@", strTemp);
[self.arrDescription addObject:strTemp];
}
if ([elementName isEqualToString:@"NEWSARTICLEDATE"])
{
NSLog(@"temstring=== %@", strTemp);
[self.arrDate addObject:strTemp];
}
if ([elementName isEqualToString:@"PUBLISHINGPAGEIMAGE"])
{
NSURL *PUBLISHINGPAGEIMAGE = [NSURL URLWithString:@"strImage"];
NSData *data = [NSData dataWithContentsOfURL:PUBLISHINGPAGEIMAGE];
UIImage *arrImages = [[UIImage alloc] initWithData:data];
NSLog(@"temstring=== %@", strTemp);
[self.arrImages addObject:strTemp];
}
if ([elementName isEqualToString:@"ShuraNews"])
{
[self.tblNews reloadData];
}
}
#pragma mark - TabeView Datasource//delegate method
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.arrTitles count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView setSeparatorInset:UIEdgeInsetsZero];
static NSString *cellIdentifier=@"cellNews";
NewsTableViewCell *cell=(NewsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil)
{
cell = [[NewsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
// cell.NewsTableViewCell.textColor = UIColorFromRGB(0x000000);
cell.backgroundColor=[UIColor clearColor];
}
if( [indexPath row] % 2){
cell.contentView.backgroundColor =UIColorFromRGB(0Xffffff);
}
else{
cell.contentView.backgroundColor =UIColorFromRGB (0Xdcdcdc);
}
//selectbackgroun color start
UIView *NewsTableViewCell = [[UIView alloc] initWithFrame:cell.frame];
NewsTableViewCell.backgroundColor = UIColorFromRGB(0Xdcdcdc);
cell.selectedBackgroundView = NewsTableViewCell; //select background colro end
cell.lblTitles.font = [UIFont fontWithName:@"GEEast-ExtraBold" size:12];
cell.lblTitles.text=[self.arrTitles objectAtIndex:indexPath.row];
cell.lblDescription.font =[UIFont fontWithName:@"GE SS Unique" size:12];
cell.lblDate.font=[UIFont fontWithName:@"GE SS Unique" size:12];
cell.lblDescription.text=[self.arrDescription objectAtIndex:indexPath.row];
cell.lblDate.text=[self.arrDate objectAtIndex:indexPath.row];
cell.lblTitles.textAlignment= NSTextAlignmentRight;
cell.lblDate.textAlignment = NSTextAlignmentRight;
cell.lblDescription.textAlignment = NSTextAlignmentRight;
// cell.imgNews.image = [UIImage imageNamed:@"homeh"];
// cell.imgNews.image=[self.arrImages objectAtIndex:indexPath.row];
UIImage *arrImages = [[UIImage alloc]initWithData:arrImages];
return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dict=[[NSDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:@"%@",
[self.arrTitles objectAtIndex:indexPath.row]],@"title",[NSString stringWithFormat:@"%@",
[self.arrImages objectAtIndex:indexPath.row]],@"img",[NSString stringWithFormat:@"%@",
[self.arrDescription objectAtIndex:indexPath.row]],@"Des", nil];
[self performSegueWithIdentifier:@"NewsDetailsID" sender:dict];
}
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"NewsDetailsID"])
{
((NewDetailsViewController *)segue.destinationViewController).strTitle=[sender objectForKey:@"title"];
((NewDetailsViewController *)segue.destinationViewController).strDescription=[sender objectForKey:@"Des"];
}
}
@end
我的 XML 格式是:
<ShuraNews>
<QueryProperties>...</QueryProperties>
<Articles TotalItems="256" TotalRowsExactToReturnItems="False">
<Article ItemNo="1">
<URL>
http://www.shura.bh/MediaCenter/News/CouncilNews/Pages/14-05-14(2).aspx
</URL>
<TITLE>
فيما أشاد رئيس "الشؤون الخارجية" في البرلمان الايرلندي بالتطور الاقتصادي بالمملكة .. الجشي: علاقاتنا مع ايرلندا ايجابية..ونأمل بالمزيد من التعاون البرلماني والتجاري بين البلدين
</TITLE>
<AUTHOR></AUTHOR>
<RANK>1000</RANK>
<DESCRIPTION/>
<WRITE>15/05/2014 01:05:55 ص</WRITE>
<ISDOCUMENT>1</ISDOCUMENT>
<SIZE>83798</SIZE>
<SITENAME>http://www.shura.bh/mediacenter/news/councilnews</SITENAME>
<CREATED/>
<NEWSARTICLEDATE>13/05/2014 05:00:00 م</NEWSARTICLEDATE>
<CONVENIENTPERIOD>الرابع</CONVENIENTPERIOD>
<TERM>الثالث</TERM>
<PUBLISHINGPAGEIMAGE>
<img alt="" border=1 src="/MediaCenter/News/Committees/HRC/PublishingImages/DSC_5804.JPG" width=450 style="border:1px solid">
</PUBLISHINGPAGEIMAGE>
<PUBLISHINGPAGECONTENT>
القضيبية – مجلس الشورى اكدت سعادة الدكتورة بهية جواد الجشي النائب الثاني لرئيس مجلس الشورى رئيسة لجنة الصداقة البحرينية الايرلندية بالمجلس على أن مملكة البحرين تولي اهتماما كبيرا لإقامة علاقات تعاون مع مختلف دول العالم في إطار من الاحترام المتبادل والمصالح المشتركة، مشيرة إلى أن العلاقات مع جمهورية إيرلندا تحظى بالتقدير والاعتزاز، معربة في الوقت ذاته عن أملها في أن تنعكس تلك العلاقات الإيجابية على رفع مستوى التعاون البرلماني والتجاري بين البلدين، منوهة بالدور المحوري للجان الصداقة البرلمانية على صعيد تقريب وجهات النظر وتبادل الآراء حول مختلف الموضوعات محل الاهتمام المشترك. واعربت الجشي عن ترحيبها بالزيارة التي يقوم بها سعادة السيد بات برين رئيس لجنة الشؤون الخارجية والتجارة في البرلمان الإيرلندي الى مملكة البحرين، والتي من شأنها البناء على علاقات الصداقة المتميزة والوثيقة القائمة بين البلدين، والارتقاء بها نحو مجالات أرحب من التعاون بما يخدم البلدين والشعبين الصديقين، حيث تضمنت الزيارة لقاء معالي رئيس مجلس النواب، ووزير التجارة والصناعة وبالمملكة، إلى جانب زيارة شركة الخليج لصناعة البتروكيماويات ومنطقة البحرين العالمية للاستثمار. من جانبه، أشار رئيس لجنة الشؤون الخارجية والتجارة في البرلمان الايرلندي إلى ان العلاقات القائمة بين مملكة البحرين وجمهورية ايرلندا هي علاقات ايجابية ومتنامية في مختلف المجالات، مشيدا بالتطورات الاقتصادية الجارية في مملكة البحرين، فيما اكد على اهمية الزيارة الاخيرة التي قام بها وفد لجنة الصداقة البحرينية الايرلندية بمجلس الشورى إلى جمهورية ايرلندا، وما اسهمت به الدعوة التي تلقاها من رئيسة الوفد سعادة الدكتورة بهية الجشي لزيارة المملكة في فتح القنوات لتطوير العلاقات القائمة بين مملكة البحرين وجمهورية ايرلندا.
</PUBLISHINGPAGECONTENT>
<COMMENTS>
اكدت سعادة الدكتورة بهية جواد الجشي النائب الثاني لرئيس مجلس الشورى رئيسة لجنة الصداقة البحرينية الايرلندية بالمجلس على أن مملكة البحرين تولي اهتماما كبيرا لإقامة علاقات تعاون مع مختلف دول العالم في إطار من الاحترام المتبادل والمصالح المشتركة
</COMMENTS>
<ARTICLEBYLINE/>
<PUBLISHINGROLLUPIMAGE>
<img alt="" border=1 src="/MediaCenter/News/Committees/HRC/PublishingImages/DSC_5804.JPG" style="border:1px solid">
</PUBLISHINGROLLUPIMAGE>
</Article>
</ShuraNews>
【问题讨论】:
-
与原始问题无关,但我不鼓励您进行同步网络请求(无论是原始 XML 还是图像)。如果你这样做,你的用户界面会很不稳定。例如,您应该使用
sendAsynchronousRequest。 -
另外,您可能不想将图像加载到数组中,而只是将图像 URL 保存在数组中,然后让
cellForRowAtIndexPath从服务器。我不知道你可能有多少行,但如果你有成百上千,你会遇到内存问题。通过让cellForRowAtIndexPath检索图像,您将只为可见单元实例化UIImage实例,这更加节省内存。
标签: ios objective-c nsxmlparser