用原生的网络请求

1.

用原生的网络请求_第1张图片

2.


用原生的网络请求_第2张图片

复制:

1.NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];

    NSURL *url = [NSURL URLWithString:@"https://pixabay.com/api/?key=4572819-33c1e1dcbac7521c915689a81&&image_type=photo"];


    NSURLRequest *repuest = [NSURLRequest requestWithURL:url];

    NSURLSessionDataTask *task = [session dataTaskWithRequest:repuest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {


        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];

        NSMutableArray *urlS = [NSMutableArray array];

        for (NSDictionary *dict in result[@"hits"]) {

            NSString *linkurl = dict[@"webformatURL"];

            [urlS addObject:linkurl];

        }

        _URLStrings = urlS;

        dispatch_async(dispatch_get_main_queue(), ^{


            [self.collectionView reloadData];

        });


    }];

    [task resume];

2.

- (void)lqPostRequestByServiceName:(NSString *)service

                          andAppi:(NSString *)api

                            parmas:(NSDictionary *)parmas

                        succeBlock:(void(^)(id _Nullable response))succeBlock

                        errorBlock:(void(^)(id _Nullable error))errorBlock{

    NSString *urlStr = [service stringByAppendingString:api];

    NSURL *url = [NSURL URLWithString:urlStr];

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

    [request setHTTPMethod:@"POST"];

    NSArray *allKeysArr = [parmas allKeys];

    NSMutableString *result = [NSMutableString string];

    for (NSString *keyStr in allKeysArr) {

        NSString *str = [NSString stringWithFormat:@"%@=%@&",keyStr,parmas[keyStr]];

        [result appendString:str];

    }

    NSString *targetStr = [result substringWithRange:NSMakeRange(0,result.length - 1)];

    NSData *targetData = [targetStr dataUsingEncoding:NSUTF8StringEncoding];

    [request setHTTPBody:targetData];

    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

    [request setValue:[NSString stringWithFormat:@"%ld",targetData.length] forHTTPHeaderField:@"Content-Length"];

    request.timeoutInterval = 10;

    NSURLSession *session = [NSURLSession sharedSession];

    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {

        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

        if (dic) {

            succeBlock(dic);

        }else{

            errorBlock(error.description);

        }

    }];

    [dataTask resume];

}

你可能感兴趣的:(用原生的网络请求)