iOS 원본 HTTP 네트워크 요청 (get / post) 다운로드 작업

5682 단어 iOS 개발 노트
자주 쓰 지 않 으 면 잊 어 버 리 고 와 보면 생각 납 니 다.
  info. plist 파일 에서 조작 하기


1. GET 요청
NSString *path = @"http://apis.juhe.cn/mobile/get?phone=13301388888&key=4e602dad4a05b4d491ffb82511613158";
//                URL  
    path = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

    NSURL *url = [NSURL URLWithString:path];
    //    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //        
    NSURLSession *session = [NSURLSession sharedSession];
    //                      
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //data         
//        NSString *string = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//        NSLog(@"%@",string);

        //       json         
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSDictionary *resultDic = dic[@"result"];
        NSString *province = resultDic[@"province"];
        NSString *city = resultDic[@"city"];
        NSString *company = resultDic[@"company"];
        NSLog(@"%@  %@   %@",province,city,company);
    }];
    //    
    [dataTask resume];
2. POST 요청
//  POST         Get  
 NSString *path = @"http://v.juhe.cn/joke/randJoke.php";
    NSURL *url = [NSURL URLWithString:path];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //       POST
    [request setHTTPMethod:@"POST"];
    //           
    [request setHTTPBody:[@"key=8d0bde7167db666ac160191217840b5b&type=pic" dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"%@",dic);
    }];    [task resume];

3. 퀘 스 트 다운로드
//        (    )
NSString *path = @"http://pic2.desk.chinaz.com/file/10.03.10/5/rrgaos36.jpg";
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
    NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        //location            tmp    
        NSLog(@"%@",location);
        NSURL *newLocation = [NSURL fileURLWithPath:@"/Users/tarena/Desktop/a.jpg"];
        NSFileManager *fm = [NSFileManager defaultManager];
        //        
        [fm moveItemAtURL:location toURL:newLocation error:nil];
    }];
    [task resume];
//         
//    
@property (weak, nonatomic) IBOutlet UIProgressView *myPV;//    
NSString *path = @"http://pic2.desk.chinaz.com/file/10.03.10/5/rrgaos36.jpg";
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:path]];
    //          
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
//                                                
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request];
    [task resume];
//        
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
      didWriteData:(int64_t)bytesWritten
 totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
    //                   
    NSLog(@"%lld   %lld  %lld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite);
    self.myPV.progress = totalBytesWritten*1.0/totalBytesExpectedToWrite;
}
//                  
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location{
    NSURL *newLocation = [NSURL fileURLWithPath:@"/Users/tarena/Desktop/bbb.jpg"];
    //        
    [[NSFileManager defaultManager]moveItemAtURL:location toURL:newLocation error:nil];
    UIImageView *iv = [[UIImageView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    //     NSData   image
    iv.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:newLocation.path]];
    [self.view addSubview:iv];
    
}

/ / 배경 에서 작업 을 다운로드 할 수 있 습 니 다 (프로 토 콜 이 있 는 방법 을 사용 해 야 합 니 다)
//          
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"download"];
//  AppDelegate.m                                                
-(void)application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler{
    NSLog(@"%@",identifier);
}

좋은 웹페이지 즐겨찾기