基础Network Request

1:NSData + NSURL

- (void)FF_LoadImageWithURLString:(NSString *)urlStr imageBlock:(ImageBlock)imageRequestCompleteBlock {
    if (urlStr && urlStr.length > 0) {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlStr]];
            dispatch_async(dispatch_get_main_queue(), ^{
                imageRequestCompleteBlock([UIImage imageWithData:data]);
            });
        });
    }
}

*  通过NSMutableRequest 来指定请求的方式(HTTPMethod)请求体(HTTPBody)等

2: NSURLConnection (已经被废弃)

可以通过Block或者delegate的形式来获取请求完成的数据

- (void)FF_loadDataUseNSURLConnection:(NSString *)url block:(ImageBlock)completeBlock {
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    /// 异步请求
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        /// 在主线程中
        completeBlock([UIImage imageWithData:data]);
    }];
    NSLog(@"是异步执行");
}

deleaget形式

- (void)FF_LoadDataUseNSURLConnectionDelegate:(NSString *)url block:(ImageBlock)completeBlock {
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.HTTPMethod = @"post";
    request.HTTPBody = [@"" dataUsingEncoding:NSUTF8StringEncoding];
    [NSURLConnection connectionWithRequest:request delegate:self];
    self.needBlcok = completeBlock;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    long mm = response.expectedContentLength;
    
    self.mdata = [NSMutableData data];
    
    NSLog(@"收到响应 %.2f", mm / 1024.0 / 1024);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.mdata appendData:data];
    NSLog(@"收到数据");
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    self.needBlcok([UIImage imageWithData:self.mdata]);
    NSLog(@"借宿请求");
}

3: NSURLSession

- (void)FF_LoadDataUseNSURLSession:(NSString *)url block:(ImageBlock)completeblock {
    [NSURLSession sharedSession];
    //NSURLSessionDataTask NSURLSessionUploadTask NSURLSessionDownloadTask
    
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:url] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            // 将JSON数据转化成Object
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@", dic);
//            completeblock([UIImage imageWithData:data]);
        });
    }];
    [task resume];
}

delegate形式

- (void)FF_LoadDataUseNSURLSessionDelgate:(NSString *)url block:(ImageBlock)completeBlock {
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *task = [session dataTaskWithURL:[NSURL URLWithString:url]];
    self.needBlcok = completeBlock;
    [task resume];
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
didReceiveResponse:(NSURLResponse *)response
 completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler {
    self.mdata = [NSMutableData data];
    /// 允许响应
    completionHandler(NSURLSessionResponseAllow);
    NSLog(@"开始响应");
}

- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
    didReceiveData:(NSData *)data {
    [self.mdata appendData:data];
    NSLog(@"收到数据");
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
didCompleteWithError:(nullable NSError *)error {
    if (error == nil) {
        self.needBlcok([UIImage imageWithData:self.mdata]);
    }
    NSLog(@"完成请求");
}

- (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error {
    NSLog(@"出现错误 %@", error.localizedDescription);
}

猜你喜欢

转载自www.cnblogs.com/jisa/p/9301520.html
今日推荐