首页 > 代码库 > 百度美图

百度美图

 摘要

      使用百度API获取美图,然后使用JSONKit解析获取的结果,最后使用SDWebImage展示图片,当然也可以使用[UIImage imageWithData:[NSData dataWithContentsOfURL:url]]显示图片,不过开源的SDWebImage在这有点大材小用。使用手势左滑和右滑实现图片切换。


结果展示

技术分享

主要技术点

  • 使用第三方开源库。本来想自己直接把源代码加到工程里面的,然后自己配置库、框架之类的,发现挺麻烦的,各种出错。后来发现了第三方开源库管理工具cocoapods,试了下效果过程都还可以,所以直接用了这个工具配置文中所用的第三方开源库,以后全部的开发就在.xcworkspace打开的工程里面开发调试了。cocoapods使用方法如下所示:

xxx $ : gem sources --remove https://rubygems.org/ # 移除官方下载链接,因为被墙
xxx $ : $ gem sources -a http://ruby.taobao.org/ # 添加国内可用下载链接
xxx $ : sudo gem install cocoapods  # 安装
xxx-baiduImageShow $ : touch Podfile # 在项目根目录新建文件,文件内容为
    ```
      1 platform :ios, '6.1'
      2 pod 'SDWebImage', '~>3.6'
      3 pod 'JSONKit'
    ```
xxx-baiduImageShow $ : pod install # 构建第三方库,生成.xcworkspace工程文件
  • 第三方开源库`JSONKit`编译的时候需要把isa关闭,否则会出错(IOS6以上的版本)。[解决方法](http://blog.csdn.net/hemuhan/article/details/17753453)为:从项目中搜索 Direct usage of ‘isa‘ YES(treat as error) 改为NO 


  • 获取百度图片的时候,发现pn代表的不是页,而是开始的索引号。


主要代码

//
//  ViewController.m
//  baiduImageShow
//
//  Created by wangwei on 14/12/30.
//  Copyright (c) 2014年 arbboter. All rights reserved.
//

#import "ViewController.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <JSONKit/JSONKit.h>

#define SDWebImage

@interface ViewController ()

@property (nonatomic, strong) UIImageView* baiduImage;
@property (nonatomic, strong) UISwipeGestureRecognizer* toLeft;
@property (nonatomic, strong) UISwipeGestureRecognizer* toRight;
@property (nonatomic, strong) NSMutableArray* baiduImageArray;
@property (nonatomic, strong) NSString* baiduImageResult;
@property (nonatomic, readwrite) NSInteger currentImageIndex;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    _baiduImage = [[UIImageView alloc] initWithFrame:self.view.frame];
    _baiduImage.contentMode = UIViewContentModeScaleAspectFill;
    _baiduImage.userInteractionEnabled = YES;
    [self.view addSubview:_baiduImage];
    
    /** 右滑手势 */
    _toRight = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(imageWillChange:)];
    _toRight.direction = UISwipeGestureRecognizerDirectionRight;
    
    /** 左滑手势 */
    _toLeft = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(imageWillChange:)];
    _toLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    
    [_baiduImage addGestureRecognizer:_toLeft];
    [_baiduImage addGestureRecognizer:_toRight];
    
    
    _baiduImageArray = [[NSMutableArray alloc] init];
    _currentImageIndex = 0;
    
    NSURL* url = [[NSURL alloc] initWithString:@"http://b.hiphotos.baidu.com/image/pic/item/aa18972bd40735fa7ffc3dc29d510fb30f2408b8.jpg"];
    _baiduImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
    
}

- (void) updateImage
{
    /** 预加载 */
    if(_baiduImageArray.count-_currentImageIndex<5)
    {
        static NSInteger pn = 0;
        NSInteger pageNum=20;
        [self addMoreImage:[NSString stringWithFormat:@"http://image.baidu.com/channel/listjson?pn=%ld&rn=%ld&tag1=美女&tag2=全部&ftags=校花&ie=utf8", pn, pageNum]];
        pn += pageNum;
    }
}

/**
 *  从网络请求新的图片
 *
 *  @param urlString 请求地址
 */
- (void) addMoreImage:(NSString*)urlString
{
    /** 转换成utf-8格式的请求 */
    _baiduImageResult = nil;
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL* url = [[NSURL alloc] initWithString:urlString];
    NSURLRequest* request = [[NSURLRequest alloc] initWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];
}

#pragma NSURLConnectionDelegate协议
// 收到数据调用该方法,可能不是一次性收到所有数据,所以..
- (void)connection:(NSURLConnection *)connection
    didReceiveData:(NSData *)data
{
    NSString* str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    
    if([_baiduImageResult length])
    {
        _baiduImageResult  = [_baiduImageResult stringByAppendingString:str];
    }
    else
    {
        _baiduImageResult = str;
    }
}

// 数据接收完成调用该方法
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    /** 利用JSONKit的NSString扩展解码 */
    NSDictionary* dict = [_baiduImageResult objectFromJSONString];
    
    //NSLog(@"result ->\n%@", dict);
    
    NSArray *array = [dict objectForKey:@"data"];
    NSString* url = nil;
    for (NSInteger i=1; i<array.count; i++)
    {
        url = [[array objectAtIndex:i-1] objectForKey:@"image_url"];
        [_baiduImageArray addObject:url];
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"Request failed -> %@", error.description);
}

/**
 *  滑动切换图片时的事件处理
 *
 *  @param sender 手势发送者
 */
- (void)imageWillChange:(id)sender
{
    if (sender == _toRight)
    {
        if(_currentImageIndex-2 >= 0)
        {
            _currentImageIndex--;
            [_baiduImage sd_setImageWithURL:[_baiduImageArray objectAtIndex:_currentImageIndex-1]];
        }
    }
    else if(sender == _toLeft)
    {
        [self updateImage];
        
        if(_currentImageIndex < _baiduImageArray.count)
        {
#ifdef SDWebImage
            NSURL* url = [[NSURL alloc] initWithString:@"http://b.hiphotos.baidu.com/image/pic/item/aa18972bd40735fa7ffc3dc29d510fb30f2408b8.jpg"];
            
            [_baiduImage sd_setImageWithURL:[_baiduImageArray objectAtIndex:_currentImageIndex++] placeholderImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:url]]];
#else
            NSURL* url = [[NSURL alloc] initWithString:[_baiduImageArray objectAtIndex:_currentImageIndex++]];
            _baiduImage.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:url]];
#endif
        }
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end


百度美图