06-网络(4)

2017-03-08  本文已影响13人  cdd48b9d36e0

0716UIWebViewJS转OC离线断点

1、OC调用JS

主要方法就是- (nullable NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script;

2、JS调用OC

先在JS中写上

<script>
            function login()
            {
                // 让webView跳转到百度页面(加载百度页面)
                location.href = 'xmg://openCamera';
            }
 </script>

再在OC中的webView的代理方法中

/**
 * 通过这个方法完成JS调用OC
 * JS和OC交互的第三方框架:WebViewJavaScriptBridge
 */
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *url = request.URL.absoluteString;
    NSString *scheme = @"xmg://";
    if ([url hasPrefix:scheme]) {
        
        NSString *methodName = [url substringFromIndex:scheme.length];
        [self performSelector:NSSelectorFromString(methodName) withObject:nil];
        
        return NO;
    }
    
    NSLog(@"想加载其他请求,不是想调用OC的方法");
    
    return YES;
}

3、Xcode中强制忽略警告(07-js调用oc03-2个参数)

// 去除Xcode编译警告
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-performSelector-leaks"
//这里写要忽略的代码,"-Warc-performSelector-leaks"是忽略类型
#pragma clang diagnostic pop

4、利用NSInvocation实现performSelector无限参数(08-js调用oc04-多个参数)

5、关于拦截异常,崩溃统计和闪退处理(09-异常处理-11-程序闪退处理)

拦截异常有两种

//用关键字抛
@throw [NSException exceptionWithName:@"haha" reason:@"数组越界" userInfo:nil];
//直接抛
[NSException raise:@"haha" format:@"数组越界"];
@try {
        @autoreleasepool {
            return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
        }
    } @catch (NSException *exception) {
        NSLog(@"main------%@", [exception callStackSymbols]);
    }

崩溃统计实现的思路是在崩溃的时刻记录到沙盒里,然后下次启动程序的时候发送到服务器

void handleException(NSException *exception)
{
    NSMutableDictionary *info = [NSMutableDictionary dictionary];
    info[@"callStack"] = [exception callStackSymbols]; // 调用栈信息(错误来源于哪个方法)
    info[@"name"] = [exception name]; // 异常名字
    info[@"reason"] = [exception reason]; // 异常描述(报错理由)
//    [info writeToFile:<#(NSString *)#> atomically:<#(BOOL)#>];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    // 将沙盒中的错误信息传递给服务器
    
    // 设置捕捉异常的回调
    NSSetUncaughtExceptionHandler(handleException);
    
    return YES;
}

闪退处理:闪退前可以提示用户要闪退了,让用户知道操作了哪一步导致闪退,虽然闪退是种很差的用户体验,但是尽量还是不要规避闪退

void handleException(NSException *exception)
{
    [[UIApplication sharedApplication].delegate performSelector:@selector(handle)];
}

- (void)handle
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"哈哈" message:@"傻逼了把" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
    [alertView show];
    
    // 重新启动RunLoop
    [[NSRunLoop currentRunLoop] addPort:[NSPort port] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"-------点击了好的");
    exit(0);
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 设置捕捉异常的回调
    NSSetUncaughtExceptionHandler(handleException);
    
    return YES;
}

6、断点下载(这个功能AFN并没有实现,AFN的上传不错)

// 所需要下载的文件的URL
#define XMGFileURL @"http://120.25.226.186:32812/resources/videos/minion_01.mp4"

// 文件名(沙盒中的文件名)
#define XMGFilename XMGFileURL.md5String

// 文件的存放路径(caches)
#define XMGFileFullpath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:XMGFilename]

// 存储文件总长度的文件路径(caches)
#define XMGTotalLengthFullpath [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"totalLength.xmg"]

// 文件的已下载长度
#define XMGDownloadLength [[[NSFileManager defaultManager] attributesOfItemAtPath:XMGFileFullpath error:nil][NSFileSize] integerValue]

#import "ViewController.h"
#import "NSString+Hash.h"
#import "UIImageView+WebCache.h"

@interface ViewController () <NSURLSessionDataDelegate>
/** 下载任务 */
@property (nonatomic, strong) NSURLSessionDataTask *task;
/** session */
@property (nonatomic, strong) NSURLSession *session;
/** 写文件的流对象 */
@property (nonatomic, strong) NSOutputStream *stream;
/** 文件的总长度 */
@property (nonatomic, assign) NSInteger totalLength;
@end

@implementation ViewController

- (NSURLSession *)session
{
    if (!_session) {
        _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    }
    return _session;
}

- (NSOutputStream *)stream
{
    if (!_stream) {
        _stream = [NSOutputStream outputStreamToFileAtPath:XMGFileFullpath append:YES];
    }
    return _stream;
}

- (NSURLSessionDataTask *)task
{
    if (!_task) {
        NSInteger totalLength = [[NSDictionary dictionaryWithContentsOfFile:XMGTotalLengthFullpath][XMGFilename] integerValue];
        if (totalLength && XMGDownloadLength == totalLength) {
            NSLog(@"----文件已经下载过了");
            return nil;
        }
        
        // 创建请求
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]];
        
        // 设置请求头
        // Range : bytes=xxx-xxx
        NSString *range = [NSString stringWithFormat:@"bytes=%zd-", XMGDownloadLength];
        [request setValue:range forHTTPHeaderField:@"Range"];
        
        // 创建一个Data任务
        _task = [self.session dataTaskWithRequest:request];
    }
    return _task;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    NSLog(@"%@", XMGFileFullpath);
}

/**
 * 开始下载
 */
- (IBAction)start:(id)sender {
    // 启动任务
    [self.task resume];
}

/**
 * 暂停下载
 */
- (IBAction)pause:(id)sender {
    [self.task suspend];
}

#pragma mark - <NSURLSessionDataDelegate>
/**
 * 1.接收到响应
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSHTTPURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    // 打开流
    [self.stream open];
    
    // 获得服务器这次请求 返回数据的总长度
    self.totalLength = [response.allHeaderFields[@"Content-Length"] integerValue] + XMGDownloadLength;
    
    // 存储总长度
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:XMGTotalLengthFullpath];
    if (dict == nil) dict = [NSMutableDictionary dictionary];
    dict[XMGFilename] = @(self.totalLength);
    [dict writeToFile:XMGTotalLengthFullpath atomically:YES];
    
    // 接收这个请求,允许接收服务器的数据
    completionHandler(NSURLSessionResponseAllow);
}

/**
 * 2.接收到服务器返回的数据(这个方法可能会被调用N次)
 */
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    // 写入数据
    [self.stream write:data.bytes maxLength:data.length];
    
    // 下载进度
    NSLog(@"%f", 1.0 * XMGDownloadLength / self.totalLength);
}

/**
 * 3.请求完毕(成功\失败)
 */
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    // 关闭流
    [self.stream close];
    self.stream = nil;
    
    // 清除任务
    self.task = nil;
}
上一篇下一篇

猜你喜欢

热点阅读