美文网首页
NSURLConnection使用RAC

NSURLConnection使用RAC

作者: csp | 来源:发表于2017-06-23 21:46 被阅读11次

    +(RACSignal *)requestPhotoData
    {
    NSURLRequest *request = [self popularURLRequest];

    return [[NSURLConnection rac_sendAsynchronousRequest:request] reduceEach:^id(NSURLResponse *response, NSData *data){
        return data;
    }];
    

    }
    创建一个URLConnection请求之后返回的数据信号。

    +(RACSignal *)importPhotos {
    return [[[[[self requestPhotoData]
    deliverOn:[RACScheduler mainThreadScheduler]]
    map:^id(NSData *data) {
    id results = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

        return [[[results[@"photos"] rac_sequence] map:^id(NSDictionary *photoDictionary) {
            FRPPhotoModel *model = [FRPPhotoModel new];
            
            [self configurePhotoModel:model withDictionary:photoDictionary];
            [self downloadThumbnailForPhotoModel:model];
            
            return model;
        }] array];
    }] publish] autoconnect];
    

    }
    deliverOn用来操作线程;
    rac_sequence用来序列化,通常用在数组上;
    configurePhotoModel:withDictionary用来把NSDictionary转成Model;
    array是把序列化重新转成数组
    publish和autoconnect是为了解决多次请求,假如一个信号中发送请求,那么每次订阅都会发送请求,publish保存订阅到数组,当调用连接autoconnect,就会调用所有的订阅者的sendNext。

    相关文章

      网友评论

          本文标题:NSURLConnection使用RAC

          本文链接:https://www.haomeiwen.com/subject/fthhcxtx.html