Fork me on GitHub

知识补充一. 字典转模型, WebView的使用,(解决Xcode7,旧项目无法正常加载网络数据问题)

一.字典转模型(以后就用这种方法)

//定义在model.h中
- (instancetype)initWithDictionary:(NSDictionary *)dict;

//在model.m中
- (instancetype)initWithDictionary:(NSDictionary *)dict { if (self = [super init]) { [self setValuesForKeysWithDictionary:dict]; } return self; }
//setValue: forUndefinedKey: 在model.m中是必须写的方法
-(void)setValue:(id)value forUndefinedKey:(NSString *)key { //if ([key isEqualToString:@"id"]) { // self.movieId = value; // } }

//调用 NewsModel
*model = [[NewsModel alloc] initWithDictionary:dict];

 

 

二.WebView的使用

<UIWebViewDelegate>
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UIActivityIndicatorView *activityIndicator;
//    初始化UIWebView
    _webView = [[UIWebView alloc] initWithFrame:self.view.frame];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://baidu.com"]];
    [self.view addSubview:_webView];
    [_webView loadRequest:request];
//    UIWebView有3个代理方法 学要遵循UIWebViewDelegate协议
    self.webView.delegate = self;

#pragma -mark webViewDelegate
//加载前 判断是否加载
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
    NSLog(@"网页开始加载");
//在加载等待页面 出现小菊花
//    创建背底半透明View
    UIView *view = [[UIView alloc] initWithFrame:self.view.frame];
    view.tag = 108;
    view.backgroundColor = [UIColor blackColor];
    view.alpha = 0.5;
    [self.view addSubview:view];
//    初始化UIActivityIndicatorView
    self.activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 0, 0)];
    [view addSubview:self.activityIndicator];
    self.activityIndicator.center = view.center;
//    设置UIActivityIndicatorView的样式
    self.activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
//    开始显示
    [self.activityIndicator startAnimating];

}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"网页加载完成");
//    通过tag值找到view 并将它移除
    UIView *view = [self.view viewWithTag:108];
    [view removeFromSuperview];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    NSLog(@"网页加载出错,error:%@", error);
    UIView *view = [self.view viewWithTag:108];
    [view removeFromSuperview];
}

 

 三.解决Xcode7,旧项目无法正常加载网络数据问题:

解决办法一.

在plist文件中添加项NSAPPTransportSecurity,类型为字典。

添加子项NSAllowsArbitraryLoads,类型为Boolean,值为YES。

 

解决办法二:

在plist文件中,进行如下配置(放在后面即可)

<key>NSAppTransportSecurity</key>
<dict>
   <key>NSAllowsArbitraryLoads</key>
   <true/>
</dict>

 

 

 
 
 
 
 
posted @ 2015-10-29 17:59  DengHuiCheng  阅读(214)  评论(0编辑  收藏  举报