如何获取xml图像并在UIcollectionview中显示? (将Json的代码更改为XML)

时间:2013-01-12 14:38:33

标签: iphone ios objective-c xml-parsing uicollectionview

我是新手xcode程序员。

我已经阅读了使用Flickr Json显示collectionview的教程。 这是两个链接:http://www.raywenderlich.com/22324/beginning-uicollectionview-in-ios-6-part-12

http://www.raywenderlich.com/22417/beginning-uicollectionview-in-ios-6-part-22

但是现在我想为Danbooru创建一个collectionview,这个网站只显示XML。

上面的教程使用4个作者制作的文件,(Flickr.h,Flickr.m,FlickrPhoto.h,FlickrPhoto.m)

我认为Flickr.m文件是该应用程序中的关键部分,因此将引用该代码:

#import "Flickr.h"
#import "FlickrPhoto.h"

#define kFlickrAPIKey @"d02c877c0a4220890f14fc95f8b16983"

@implementation Flickr

+ (NSString *)flickrSearchURLForSearchTerm:(NSString *) searchTerm
{
searchTerm = [searchTerm stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return [NSString stringWithFormat:@"http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=%@&text=%@&per_page=20&format=json&nojsoncallback=1",kFlickrAPIKey,searchTerm];
}

+ (NSString *)flickrPhotoURLForFlickrPhoto:(FlickrPhoto *) flickrPhoto size:(NSString *) size
{
if(!size)
{
    size = @"m";
}
return [NSString stringWithFormat:@"http://farm%d.staticflickr.com/%d/%lld_%@_%@.jpg",flickrPhoto.farm,flickrPhoto.server,flickrPhoto.photoID,flickrPhoto.secret,size];
}

- (void)searchFlickrForTerm:(NSString *) term completionBlock:(FlickrSearchCompletionBlock) completionBlock
{
NSString *searchURL = [Flickr flickrSearchURLForSearchTerm:term];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{
    NSError *error = nil;
    NSString *searchResultString = [NSString stringWithContentsOfURL:[NSURL URLWithString:searchURL]
                                                       encoding:NSUTF8StringEncoding
                                                          error:&error];
    if (error != nil) {
        completionBlock(term,nil,error);
    }
    else
    {
        // Parse the JSON Response
        NSData *jsonData = [searchResultString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *searchResultsDict = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                          options:kNilOptions
                                                                            error:&error];
        if(error != nil)
        {
            completionBlock(term,nil,error);
        }
        else
        {
            NSString * status = searchResultsDict[@"stat"];
            if ([status isEqualToString:@"fail"]) {
                NSError * error = [[NSError alloc] initWithDomain:@"FlickrSearch" code:0 userInfo:@{NSLocalizedFailureReasonErrorKey: searchResultsDict[@"message"]}];
                completionBlock(term, nil, error);
            } else {

                NSArray *objPhotos = searchResultsDict[@"photos"][@"photo"];
                NSMutableArray *flickrPhotos = [@[] mutableCopy];
                for(NSMutableDictionary *objPhoto in objPhotos)
                {
                    FlickrPhoto *photo = [[FlickrPhoto alloc] init];
                    photo.farm = [objPhoto[@"farm"] intValue];
                    photo.server = [objPhoto[@"server"] intValue];
                    photo.secret = objPhoto[@"secret"];
                    photo.photoID = [objPhoto[@"id"] longLongValue];

                    NSString *searchURL = [Flickr flickrPhotoURLForFlickrPhoto:photo size:@"m"];
                    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:searchURL]
                                                              options:0
                                                                error:&error];
                    UIImage *image = [UIImage imageWithData:imageData];
                    photo.thumbnail = image;

                    [flickrPhotos addObject:photo];
                }

                completionBlock(term,flickrPhotos,nil);
            }
        }
    }
});
}

+ (void)loadImageForPhoto:(FlickrPhoto *)flickrPhoto thumbnail:(BOOL)thumbnail completionBlock:(FlickrPhotoCompletionBlock) completionBlock
{

NSString *size = thumbnail ? @"m" : @"b";

NSString *searchURL = [Flickr flickrPhotoURLForFlickrPhoto:flickrPhoto size:size];
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_async(queue, ^{
    NSError *error = nil;

    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:searchURL]
                                              options:0
                                                error:&error];
    if(error)
    {
        completionBlock(nil,error);
    }
    else
    {
        UIImage *image = [UIImage imageWithData:imageData];
        if([size isEqualToString:@"m"])
        {
            flickrPhoto.thumbnail = image;
        }
        else
        {
            flickrPhoto.largeImage = image;
        }
        completionBlock(image,nil);
    }

});
}



@end

这就是Json的代码, 通过搜索,我找到了一种用TBXML(opensource)解析XML的方法

通过在另一个测试项目的viewController中实现下面的代码,我可以在调试屏幕上看到图像的URL:

void (^tbxmlSuccessBlock)(TBXML *) = ^(TBXML * tbxml){
TBXMLElement *elemRoot = nil, *elemImage = nil ;
elemRoot = tbxml.rootXMLElement;

if(elemRoot){
    elemImage = [TBXML childElementNamed:@"post" parentElement:elemRoot];

    while(elemImage){{
        NSString *localURL = [TBXML valueOfAttributeNamed:@"file_url" forElement:elemImage];
        NSLog(@"Local : %@", localURL);

       NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:localURL]];
        UIImage *image = [UIImage imageWithData:imageData];


        weatherPhoto.largeImage = image;
        elemImage=elemImage->nextSibling;
    }}
}};
void (^tbxmlFailureBlock) (TBXML *, NSError *) = ^(TBXML * tbxml, NSError * error){
NSLog(@"Error: %@", error);
};
- (void)parseXML{
NSURL *imageURL = [NSURL URLWithString:@"http://safebooru.org/index.php?page=dapi&s=post&q=index&limit=5"];
[TBXML newTBXMLWithURL:imageURL success:tbxmlSuccessBlock failure:tbxmlFailureBlock];}



- (void)viewDidLoad
{
[super viewDidLoad];


// 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;
[NSThread detachNewThreadSelector:@selector(parseXML) toTarget:self withObject:nil];

}

到目前为止,这就是我得到的所有内容。 如何更改Flickr.m并使XML中的图像显示在UIcollectionView?

1 个答案:

答案 0 :(得分:1)

所以我再次阅读你的问题,并意识到你问了别的东西。您是否在询问如何使Flickr.m从XML加载图像?你没有。此类用于加载flickr照片。你需要编写自己的类,它知道如何从XML中提取url并使用我给你的例子加载图像。


您需要创建一个UIImage实例并异步加载它 例如:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
    NSData * imageData = [NSData dataWithContentsOfURL:self.URL];
    self.image = [UIImage imageWithData:imageData];

    dispatch_async(dispatch_get_main_queue(), ^{
        if (self.image)
            [self setupImageView];
    });

您还可以使用NSOperationQueue或NSURLConnection来执行异步数据加载。