如何在没有互联网连接时显示图像(Web视图)

时间:2014-05-15 05:32:43

标签: xcode

我有一个基于Web视图的程序,我刚刚测试。没有互联网连接时如何显示图像?

我有一个基本的网页浏览

    //
//  XYZViewController.m
//  Phantomore
//
//  Created by Kevin Jin on 5/15/14.
//  Copyright (c) 2014 Kevin Jin. All rights reserved.
//

#import "XYZViewController.h"

@interface XYZViewController ()

@end

@implementation XYZViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *fullURL = @"http://www.phantomore.com";
    NSURL *url = [NSURL URLWithString:fullURL];
    NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
    [_viewWeb loadRequest:requestObj];
}

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

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

@end

多数民众赞成,我只是想知道当没有互联网连接时我必须做些什么让它显示图像

2 个答案:

答案 0 :(得分:0)

有两种方法可以做到。

  1. 在执行网址请求之前,请检查互联网连接是否可用。使用Apple provided Reachability classes或更好地使用open-source version。如果互联网可用,请加载请求。如果没有添加UIImageView与您首选的UIImage作为webview的子视图。你可以这样做:

    //inside @interface
    @property(nonatomic, strong) UIImageView *imageView;
    
    //inside -(void)viewDidLoad
    self.imageView = [UIImageView alloc] initWithImage:[UIImage imageNamed:@"as.as"];
    Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];
    reach.reachableBlock = ^(Reachability*reach) {
        // load request
    NSString *fullURL = @"http://www.phantomore.com";
        NSURL *url = [NSURL URLWithString:fullURL];
        NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
        [_viewWeb loadRequest:requestObj];
    };
    
    reach.unreachableBlock = ^(Reachability*reach) {
        //show imageview
        [_viewWeb addSubView:self.imageView];
    };
    [reach startNotifier];
    
  2. 实施UIWebView delegate。在 - webView:didFailLoadWithError:方法中,检查错误。如果错误是由无互联网连接引起的,请添加imageview(与之前相同)。

答案 1 :(得分:0)

我刚刚简化了mamnun的答案(Get Reachability here)。

您可以在实现可访问性类

后使用此方法
- (BOOL)isConnectedToInternet
{
    Reachability *reachability = [Reachability reachabilityForInternetConnection];
    NetworkStatus networkStatus = [reachability currentReachabilityStatus];
    return !(networkStatus == NotReachable);
}

在任何一个班级

- (void)viewDidLoad
{
    [super viewDidLoad];

    if([self isConnectedToInternet]){
       //Hide your imageview
       NSString *fullURL = @"http://www.phantomore.com";
       NSURL *url = [NSURL URLWithString:fullURL];
       NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
       [_viewWeb loadRequest:requestObj];
    }
   else{
       // Hide your webview
       // Show your imageview
       // Do not forget to import reachability class on top
   }
}