iOS 미 친 자세 한 NSURLSession 사용

4784 단어 iOS
//
//  ViewController.m
//  NSURLSession
//
//  Created by long on 15/9/11.
//  Copyright (c) 2015  WLong. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
@property(nonatomic,retain)NSMutableData *receiveData;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

//     task    resume        

- (IBAction)BlockButton:(id)sender {
    //      session  
    NSURLSession *session = [NSURLSession sharedSession];
    NSURL *url = [NSURL URLWithString:@"http://mobile.ximalaya.com/m/explore_album_list?category_name=all&condition=hot&device=android&page=1&per_page=20&status=0&tag_name=%E5%8D%81%E4%BA%8C%E6%98%9F%E5%BA%A7"];
    
    //  URL   task  block                
    NSURLSessionTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        
        NSLog(@"-----%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"result = %@",result);
    }];
    //    
    [task resume];
}



//NSURLSessionDataDelegate    
//NSURLSession   block             ,                    ,             .NSURLSession      NSURLConnection    ,        、    、        .

- (IBAction)DelegateButton:(id)sender {
    //              ,  session delegate      ,                session
    NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]];
    //    (         ,    block     )
    NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=15&udid=1234567890&terminalType=Iphone&cid=213"]]];
    
    //    
    [task resume];
}
//    :
//1.       
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
    //          ,              ,NSURLSession                   :completionHandler(NSURLSessionResponseAllow);,              ,         
    completionHandler(NSURLSessionResponseAllow);
    
    //        http   (url http  ),response    NSHTTPURLResponse   
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        
    NSLog(@"status code = %ld",httpResponse.statusCode);
    NSLog(@"all header fields = %@",httpResponse.allHeaderFields);
    
    //       data,          data  
    self.receiveData = [NSMutableData dataWithCapacity:40];
}

//2.        (      )
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    //         
    //       data  ,   receiveData 
    [_receiveData appendData:data];

}

//3.        (     error  )
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
//    ,         
    NSString *result = [[NSString alloc] initWithData:_receiveData encoding:NSUTF8StringEncoding];
    NSLog(@"result = %@",result);

}




- (IBAction)GetButton:(id)sender {
    
}




//POST GET      request,    session POST   GET      ,      request   .
- (IBAction)PostButton:(id)sender {
    
    
    
    NSURL *url= [NSURL URLWithString:@"http://ipad-bjwb.bjd.com.cn/DigitalPublication/publish/Handler/APINewsList.ashx?date=20131129&startRecord=1&len=15&udid=1234567890&terminalType=Iphone&cid=213"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod = @"POST";
    request.HTTPBody = [@"username=daka&pwd=123" dataUsingEncoding:NSUTF8StringEncoding];
    NSURLSession *session = [NSURLSession sharedSession];
    //     request     ,    request   task
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSLog(@"%@",[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil]);
        NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"result = %@",result);
    }];
    //    
    [task resume];

}





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

좋은 웹페이지 즐겨찾기