先在微博开放平台注册一个账号:http://open.weibo.com/
Json平台:http://doido.sinaapp.com/json/
微博开放平台
JSON
按了上一张图片“调用接口”绿色按钮会返回一个json内容在“返回内容”的文本框内复制一下
在我提供的json网页里面把对应的json内容放到右边的文本框,左面就会显示树形图,他是有“数组和字典组成”的一个树形图
上面那一张图片的左边形成的树形图等等会用在
WeiBoModel类的
//1.
ViewController.h
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutletUITextView *text;
@end
//2.
ViewController.m
#import "ViewController.h"
#import "WeiBoModel.h"//导入微博
/*
NSURLConnectionDataDelegate 协议里面
有三个方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
*/
@interface ViewController ()<NSURLConnectionDataDelegate>
{
NSURLConnection *connentGet;
NSURLConnection *connectionPost;
NSMutableData *mdata;
NSMutableData *mPostData;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
#pragma mark -----同步get按钮-----
//同步get
- (IBAction)syncharonuzedGet:(id)sender
{
//拿到urlString
NSString *urlString=@"(请求URL)?(请求参数)";//开发者平台
//编码
urlString=[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSetURLQueryAllowedCharacterSet]];
//转换成NSURL
NSURL *url=[NSURLURLWithString:urlString];
/*
创建分那会一个URL请求,指向一个指定的URL
<#(NSURLRequestCachePolicy)#>:缓存策略
NSURLRequestUseProtocolCachePolicy:默认的缓存策略,如果缓存不存在,直接从服务器端获取,如果
缓存存在,会根据response中的cache-Control字段判断,下一步操作:ru:Cache-Control字段为must-revalidata,则询问服务端该数据是否有更新,无更新的花直接返回给用户缓存数据,若
NSURLRequestReloadIgnoringLocalCacheData:忽略本地缓存数据,直接请求服务端
NSURLRequestReloadIgnoringLocalAndRemoteCacheData:忽略本地存缓存,代理服务器以及其他中介
NSURLRequestReloadIgnoringCacheData
NSURLRequestReturnCacheDataElseLoad:如果有缓存就使用它,不管器有效性(忽略Cache-Control字段),则请求服务端
NSURLRequestReturnCacheDataDontLoad:死活加载本地缓存,没有就失败(确定当前无网络时使用)
NSURLRequestReloadRevalidatingCacheData:缓存数据必须得到服务端确认有效性时使用
*/
NSURLRequest *request=[NSURLRequestrequestWithURL:urlcachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheDatatimeoutInterval:10];
//如果url 10s没有响应就超时
NSURLResponse *httpUrlResponse;//URL请求
NSError *error;
//在OC中使用NSURLConnection类,和服务器连接,这里是同步连接
/*
NSJSONReadingMutableContainers:返回的是可变容器
NSJSONReadingMutableLeaves:返回的Json对象中字符存得值为NSMutableString
NSJSONReadingAllowFragments:允许Json字符串最外层即不是NSArray也不是NSDictionary,但必须是有效的JSon Fragment
*/
NSData *data=[NSURLConnection sendSynchronousRequest:requestreturningResponse:&httpUrlResponseerror:&error];
//Json数据格式解析,利用系统提供的API进行Json数据解析
NSDictionary *dictionary=[NSJSONSerializationJSONObjectWithData:dataoptions:NSJSONReadingAllowFragmentserror:&error];
//NSLog(@"dictionary=%@",dictionary);
// NSArray *array= dictionary[@"statuses"];
// NSLog(@"statuses=%@",[array[0] valueForKey:@"text"]);
WeiBoModel *weibo=[[WeiBoModelalloc]initWithDictionary:dictionary];
//NSLog(@"%@",weibo.statuses[0]);//代表WeiBoModel里面的dtatuses数组里面的第一个内容
NSLog(@"%@",[weibo.statuses[0]valueForKey:@"text"]);//代表WeiBoModel里面的的statuses数组里面的第一个取里面的字典的通过key找到对于的value
self.text.text=[weibo.statuses[0]valueForKey:@"text"];//自己.控件的名字.该控件的方法;
}
//同步会卡UI
#pragma mark -----异步get按钮-----
//异步get
- (IBAction)ayncharonuzedGet:(id)sender
{
//拿到urlString
NSString *urlString=@"(请求URL)";//开发者平台
//编码
urlString=[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSetURLQueryAllowedCharacterSet]];
//转换成NSURL
NSURL *url=[NSURLURLWithString:urlString];
NSURLRequest *request=[NSURLRequestrequestWithURL:urlcachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheDatatimeoutInterval:10];
//异步请求两种方式:一种是使用代理,一种是使用block
//使用代理方式进行异步请求
//全局
connentGet=[NSURLConnectionconnectionWithRequest:requestdelegate:self];
//<NSURLConnectionDataDelegate>的代理
//使用block
// [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *_Nullable response,NSData * _Nullable data,NSError *_Nullable connectionError)
// {
// NSDictionary *dictionary=[NSJSONSerialization JSONObjectWithData:mdata options:NSJSONReadingAllowFragments error:nil];
// WeiBoModel *weibo=[[WeiBoModel alloc]initWithDictionary:dictionary];
// dispatch_async(dispatch_get_main_queue(), ^{self.text.text=[weibo.statuses[0] valueForKey:@"text"];});
// }];
}
#pragma mark -----同步post按钮-----
//同步post
- (IBAction)synPost:(id)sender
{
NSString *urlString=@"(请求URL)";
//编码
urlString=[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSetURLQueryAllowedCharacterSet]];
//转换成URL
NSURL *url=[NSURLURLWithString:urlString];
//OC中使用NSMutableURLRequest进行POST请求
NSMutableURLRequest *mRequest=[NSMutableURLRequestrequestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicytimeoutInterval:60];
NSString *bodyString=@"(请求参数)";
//bodyString=[bodyString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSData *data=[bodyString dataUsingEncoding:4];
//设置方法体
[mRequest setHTTPMethod:@"POST"];
[mRequest setHTTPBody:data];
NSData *resultData=[NSURLConnectionsendSynchronousRequest:mRequestreturningResponse:nilerror:nil];
//返回字典
NSDictionary *dictionary=[NSJSONSerializationJSONObjectWithData:resultDataoptions:NSJSONReadingAllowFragmentserror:nil];
}
#pragma mark -----异步post按钮-----
//异步post
- (IBAction)aynPost:(id)sender
{
NSString *urlString=@"(请求URL)";
//编码
urlString=[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSetURLQueryAllowedCharacterSet]];
NSURL *url=[NSURLURLWithString:urlString];
//OC中使用NSMutableURLRequest发送POST请求
NSMutableURLRequest *mAsynRequest=[NSMutableURLRequestrequestWithURL:urlcachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
NSString *bodyString=@"(请求参数)";
NSData *data=[bodyString dataUsingEncoding:4];
//设置方法体
[mAsynRequest setHTTPMethod:@"POST"];
[mAsynRequest setHTTPBody:data];
//连接全局变量
connectionPost=[NSURLConnectionconnectionWithRequest:mAsynRequestdelegate:self];
//delegate代理self代理本类的协议:协议里面有三个方法
}
#pragma mark--------------------
//服务开始响应,准备向客户发送消息
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"服务器开始响应,准备向客户发送消息");
if (connection==connentGet)
{
mdata=[NSMutableDatadata];//接收所有的数据
}
if (connection==connectionPost)
{
mPostData=[NSMutableDatadata];
}
}
//从服务器接收数据,并且此方法会执行多次
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(@"从服务器上接收数据,并且此方法会执行很多次");
if (connection==connentGet)
{
[mdataappendData:data];//数据不是一次性下载完成需要一点一点饼接起来
}
if (connection==connectionPost)
{
[mPostData appendData:data];
}
}
//接收数据完成
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{//到子线程里完成
NSLog(@"接收数据完成");
if (connection==connentGet)
{
//Json解析
NSDictionary *dictionary=[NSJSONSerializationJSONObjectWithData:mdataoptions:NSJSONReadingAllowFragmentserror:nil];//返回字典为什么是字典看Json的树形图
WeiBoModel *weibo=[[WeiBoModelalloc]initWithDictionary:dictionary];
//子线程完成回到主线程
[self.textperformSelectorOnMainThread:@selector(setText:)withObject:[weibo.statuses[0]valueForKey:@"text"]waitUntilDone:NO];
}
if (connection==connectionPost)
{
NSDictionary *dic=[NSJSONSerializationJSONObjectWithData:mPostDataoptions:NSJSONReadingAllowFragmentserror:nil];
NSLog(@"dictionary=%@",dic);
}
//self.text.text=[weibo.statuses[0] valueForKey:@"text"];//一般不这样做
//同样输出结果
/*
更新UI最后在主线程中更新,原因如下:
1.在子线程中是不能UI更新的,而可以更新的结果只是一个幻想:因为子线程代码执行
完毕,又自动进入到主线程,执行了主线程中的UI更新的函数栈,这中间的时间非常的短,就让大家误认为子线程可以更新UI,如果子线程一直在运行,者子线程中的UI更新的函数栈,主线程v获知,即无法更新
2.只有极少的UI能,因为开辟线程是回获取当前环境,如果点击某个按钮,这个按钮响应的方式是开辟一个子线程,
在子线程中对该按钮进行UI更新是能及时的如换标题,换背景图,但是这没有任何意义;
*/
}
- (void)didReceiveMemoryWarning {
[superdidReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
#import <Foundation/Foundation.h>
@interface WeiBoModel : 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 "WeiBoModel.h"
@implementation WeiBoModel
-(id)initWithDictionary:(NSDictionary *)dictionary
{
if (self = [superinit])
{
[selfsetValuesForKeysWithDictionary:dictionary];
}
return self;
}
@end