您的位置:首页 > 其它

使用异步Get在新浪微博上获取最新的微博

2015-12-29 20:15 405 查看
#import <Foundation/Foundation.h>

@interface WeiBo : NSObject
@property (nonatomic,strong) NSArray *statuses;

@property (nonatomic,strong) NSArray *advertises;

@property (nonatomic,strong) NSArray *ad;

@property (nonatomic,strong)NSNumber *hasvisible;

@property (nonatomic,strong)NSNumber *previous_cursor;

@property (nonatomic,strong)NSNumber *next_cursor;

@property (nonatomic,strong)NSNumber *total_number;

@property (nonatomic,strong)NSNumber *interval;

@property (nonatomic,strong)NSNumber *uve_blank;

@property (nonatomic,strong)NSNumber *since_id;

@property (nonatomic,strong)NSNumber *max_id;

@property (nonatomic,strong)NSNumber *has_unread;
-(id)initWithDictionary:(NSDictionary *)dictionary;

@end

#import "WeiBo.h"

@implementation WeiBo
-(id)initWithDictionary:(NSDictionary *)dictionary
{
if (self = [super init])
{
[self setValuesForKeysWithDictionary:dictionary];
}
return self;
}
@end


#import "ViewController.h"
#import "WeiBo.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
{
NSMutableData *mData;
}
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
//异步Get
- (IBAction)asynchronousGet:(id)sender {
//获取url
NSString *urlString = @"https://api.weibo.com/2/statuses/home_timeline.json?access_token=2.00bUKyMD0Spw_tebfe20df130tHaM_";
//编码
urlString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//转换成NSURL
NSURL *url = [NSURL URLWithString:urlString];
//创建并返回一个URL请求,指向一个指定的URL,采用对应的缓存策略 和 超时响应时长(默认时长60秒)
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10];
NSConnection *connectionGet = [NSURLConnection connectionWithRequest:request delegate:self];

}

//服务器开始响应,准备向客户发送信息
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
mData = [NSMutableData data];
}

//服务器接收数据,并且此方法会执行多次
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[mData appendData:data];
}

//接收数据完成
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//Json数据格式解析,利用系统提供的API进行Json数据解析
NSDictionary *dictionay = [NSJSONSerialization JSONObjectWithData:mData options:NSJSONReadingAllowFragments error:nil];
WeiBo *weibo = [[WeiBo alloc]initWithDictionary:dictionay];
[self.TextView performSelectorOnMainThread:@selector(setText:) withObject:[weibo.statuses[0] objectForKey:@"text"] waitUntilDone:NO];
}

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

@end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: