2

我是一个新手 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

但现在我想为仅显示 XML 的站点 Danbooru 制作集合视图。

上面的教程使用了 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];

}

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

4

1 回答 1

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 来执行异步数据加载。

于 2013-02-01T08:08:02.903 回答