1.
两部分:
链接并获取数据
从获取到数据构建数据模型
2.通过HTTP协议于web服务器通信
`浏览器发送一个请求给制定的url地址,url返回求情页。HTML以及图片
`浏览器发生带有其他参数的比如是表数据 给制定的服务器,服务器返回一个自定义的或者动态的活着web page
3.数据格式一般是JSON或者XML
4.请求的url格式。
一般没有特定的格式,只要服务器能识别即可。比如灰腾腾p://bookapi.bignerdranch.com/course.json
http://baseURL.com/serviceName?argumentX=valueX&argumentY=valueY
比如获取指定时间的课程内容:
http://bignerdranch.com/course?year=2014&month=11
!!!url地址不能包好空格等一些特殊字符,如果有需要,你要进行转义
NSString *search = @"Play some \"Abba\"";
NSString *escaped = [search stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
解析地址
- (NSString *)stringByRemovingPercentEncoding;
5.使用URLSession
NSURLSession *session;
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionCofiguration];
session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:nil];
创建带一个configuration以及delegate,delegateQueue 默认可以为nil
获取数据:
-(void)fetchFeed
{
NSString *requestString = @"http://bignerdranch.com/course.json";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
NSURLSessionDataTask *dataTask = [self.session dataTaskWithRequest:req
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error){
NSString *json = [[NSString alloc] stringWithData: data encoding:NSUTF8StringEncoding];
}];
[dataTask resume];
}
使用session创建dataTask
6.JSON数据
解析:使用自带原生类NSJSONSerialization,会把对应的数据转换为NS类型的,NSDictionary,NSArray,NSString,NSNumber...
^(NSData *data,NSURLResponse *response,NSError *error)
{
NSDictionary *jsonObject = [NSJSONSerialization jsonObjectWithData:data
tions:0
ror:nil];
}
// 修改tableViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self.tableView registerClass:[UITableViewCell class]
forCellReuseIdentifier:@"UITableViewCell"];
}
- (NSInteger)tableView:(UITableView *)tableView
numberOfRowsInSection:(NSInteger)section
{
return 0;
return [self.courses count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
return nil;
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"
forIndexPath:indexPath];
NSDictionary *course = self.courses[indexPath.row];
cell.textLabel.text = course[@"title"];
return cell;
}
7.主线程 Main Thread
现代苹果设备有多个处理器,所以可以存在多个代码段并发执行。
主线程有时候也叫UI线程,与处理UI相关的都要放在主线程中。
然而像上面那种做法默认将NSURLSessionDataTask就放在其他线程中处理 background thread,
****对比与上面做法的差异****
加载完后reloadData,与UI相关,如何放到主线程中运行:
dispatch_async函数
^(NSData *data,NSURLResponse *response,NSError *error)
{
NSDictionary *jsonObject = [NSJSONSerialization jsonObjectWithData:data
tions:0
ror:nil];
dispatch_async(dispatch_get_main_queue(),^{
[self.tableView reloadData];
})
}
--------------------------------------------------------
8.UIWebView
之前的每个单元格数据保留了一个具体的url,点击单元格能显示url的内容,但不需要离开应用去打开safari
// UIWebView 作为v存在一个viewController(c)中
@interface BNRWebViewController : UIViewController
@property (nonatomic) NSUR *URL;
@end
@implementation BNRWebViewController
-(void)loadView
{
UIWebView *webView = [[UIWebView alloc] init];
webView.scalePageToFit = YES;
self.view = webView;
}
-(void)setURL:(NSURL *)URL
{
_URL = URL;
if(_URL){
NSURLRequest *req = [NSURLRequest requestWithURL:_URL];
[(UIWenView *)self.view loadRequest:req];
}
}
@end
//////
在BNRCourseViewController.h中定义新属性:
@class BNRWebViewController; // 如果只是声明,引入类即可
@property (nonatomic) BNRWebViewController *webViewController;
@end
//////
在delegation 中
-(BOOL) application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)options
{
//.....code.
BNRWebViewController *wvc = [[BNRWebViewController alloc] init];
cvc.webViewController = wvc;
}
//////
@implementation BNRCourseViewController
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *course = self.courses[indexPath.row];
NSURL *url = [NSURL URLWithString:course[@"url"]];
self.webViewController.title = course[@"title"];
self.webViewController.URL = url;
[self.navigationController pushViewController:self.webViewController animated:YES];
}
9.证书 credentials
当你访问一些网站,需要授权或者是身份认证等,就不能直接获取数据,还需要中间提供验证
//需要用户名和密码
-(void)fetchFeed
{
NNString *requestString = @"https://bookapi.bignerranch.com/private/courses.json";
//code...
}
-(instancetype) initWithStyle:(UITableViewStype)style
{
//code ...
{
//code ...
_session = [NSURLSession sessionWithConfiguration:config
delegate:self
delegateQueue:nil];
[self fetchFeed];
}
return self;
}
//////
@implementation BNRCoursesViewController() <NSURLSessionDataDelegate>
// delegation method
-(void)URLSession:(NSURLSession *) session task:(NSURLSessionTask *)task
didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition,NSURLCredential *)) completionHandler
{
NSURLCredential *cred = [NSURLCredential credentialWithUser:@"BigNerdRanch" password:@"AchieveNerdvana"
persistence:NSURLCredentialPersistenceForSession
completionHandler(NSURLSessionAuthChallengeUseCredential,cred)];
}
@end
10.UIWebView 会记录浏览历史,可以使用添加UIToolbar前进后退[goBack,goForward]