App Store 获取某个App评论并存沙盒

  iOS demo

#import "ViewController.h"

@interface ViewController ()
<
UITableViewDelegate,
UITableViewDataSource
>
@property (nonatomic, strong) NSMutableArray *arr;
@property (nonatomic, strong) UILabel *label;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) NSInteger pageNo;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"%@",NSHomeDirectory());
    [self initUI];
}

-(void)initUI
{
    [self.view addSubview:self.label];
    // https://apps.apple.com/cn/app/ding-ding/id930368978
    NSString *appId;
    appId = @"930368978";
    appId = @"id930368978";

    self.pageNo = 1;
    
    [self appFromAppid:appId pageNo:self.pageNo];
}

-(void)setPageNo:(NSInteger)pageNo
{
    _pageNo = pageNo;
    _label.text = [NSString stringWithFormat:@"加载数据第 %zd 页 。。。",_pageNo];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *ident = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[UITableViewCell description]];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:ident];
    }
    cell.textLabel.font = [UIFont systemFontOfSize:17];
    cell.textLabel.numberOfLines = 0;
    cell.textLabel.text = self.arr[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *text = self.arr[indexPath.row];
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = text;
    NSLog(@"复制到剪切板");
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *str = [NSString stringWithFormat:@"%@",self.arr[indexPath.row]];
    return [self strHeightFromWidth:self.view.frame.size.width - 40 font:[UIFont systemFontOfSize:17] str:str];
}

-(CGFloat)strHeightFromWidth:(CGFloat)width font:(UIFont *)font str:(NSString *)str
{
    
    CGSize baseSize = CGSizeMake(width, CGFLOAT_MAX);
    
    if (!font)
    {
        font = [UIFont systemFontOfSize:16.0f];
    }
    
    CGSize labelsize  = [str boundingRectWithSize:baseSize
                                          options:NSStringDrawingUsesLineFragmentOrigin
                                       attributes:@{NSFontAttributeName:font}
                                          context:nil].size;
    return labelsize.height;
}

-(NSMutableArray *)arr{
    if (!_arr) {
        _arr = [NSMutableArray array];
    }
    return _arr;
}

-(UILabel *)label{
    if (!_label)
    {
        UILabel *label = [[UILabel alloc]initWithFrame:self.view.frame];
        label.text = @"数据加载中。。。";
        [label setTextAlignment:(NSTextAlignmentCenter)];
        _label = label;
    }
    return _label;
}

-(UITableView *)tableView{
    if (!_tableView) {
        
        CGRect frame = self.view.frame;
        frame.origin.y += 22;
        frame.size.height -= 22;
        
        _tableView = [[UITableView alloc]initWithFrame:frame];
        _tableView.delegate = self;
        _tableView.dataSource = self;
    }
    return _tableView;
}

-(void)appFromAppid:(NSString *)appId pageNo:(NSInteger)pageNo
{
    _pageNo = pageNo;
    
    appId = [appId stringByReplacingOccurrencesOfString:@"id" withString:@""];
    
    NSString *page = [NSString stringWithFormat:@"%zd",pageNo];
    NSString *url = [NSString stringWithFormat:@"https://itunes.apple.com/cn/rss/customerreviews/page=%@/id=%@/sortby=mostrecent/json",page,appId];
    
    __weak __typeof(&*self)weakSelf = self;;
    [self httpByUrl:url dic:nil isPost:NO success:^(id responseObject) {
        
        NSDictionary *dic = responseObject;
        
        NSDictionary *feed = [dic valueForKey:@"feed"];
        
        NSArray *entry = [feed valueForKey:@"entry"];
        for (NSDictionary *dic in entry)
        {
            NSDictionary *author = [dic valueForKey:@"author"];
            
            NSDictionary *name = [author valueForKey:@"name"];
            NSString *namelabel = [name valueForKey:@"label"];

            NSDictionary *content = [dic valueForKey:@"content"];
            NSString *contentlabel = [content valueForKey:@"label"];
            
            NSDictionary *title = [dic valueForKey:@"title"];
            NSString *titlelabel = [title valueForKey:@"label"];
            
            NSDictionary *version = [dic valueForKey:@"im:version"];
            NSString *versionlabel = [version valueForKey:@"label"];
            
            NSDictionary *rating = [dic valueForKey:@"im:rating"];
            NSString *ratinglabel = [rating valueForKey:@"label"];
            
            NSDictionary *voteSum = [dic valueForKey:@"im:voteSum"];
            NSString *voteSumlabel = [voteSum valueForKey:@"label"];

//            NSMutableDictionary *dicNew = [NSMutableDictionary dictionary];
//            [dicNew setValue:namelabel forKey:@"name"];
//            [dicNew setValue:contentlabel forKey:@"content"];
//            [dicNew setValue:titlelabel forKey:@"title"];
//            [dicNew setValue:versionlabel forKey:@"version"];
//            [dicNew setValue:ratinglabel forKey:@"rating"];
//            [dicNew setValue:voteSumlabel forKey:@"voteSum"];
            
            
            NSString *start = @"";
            
            for (int i = 0; i <[ratinglabel integerValue] ; i++)
            {
                start = [start stringByAppendingString:@"⭐️"];
            }
            
            NSString *str = [NSString string];
            str = [str stringByAppendingString:[NSString stringWithFormat:@"版本 = %@\n",versionlabel]];
            str = [str stringByAppendingString:[NSString stringWithFormat:@"星数 = %@ \n",start]];
            str = [str stringByAppendingString:[NSString stringWithFormat:@"评级 = %@ \n",ratinglabel]];
            str = [str stringByAppendingString:[NSString stringWithFormat:@"昵称 = %@\n",namelabel]];
            str = [str stringByAppendingString:[NSString stringWithFormat:@"标题 = %@\n",titlelabel]];
            str = [str stringByAppendingString:[NSString stringWithFormat:@"内容 = %@\n",contentlabel]];
            str = [str stringByAppendingString:[NSString stringWithFormat:@"投票 = %@\n",voteSumlabel]];
            
            [self.arr addObject:str];
        }
     
        NSLog(@"count = %zd",entry.count);
        
        if (entry.count > 0)
        {
            weakSelf.pageNo++;
//            NSLog(@"%zd",self.pageNo);
            [self appFromAppid:appId pageNo:weakSelf.pageNo];
        }
        else
        {
//            NSLog(@"%@",self.arr);
            [self saveText:self.arr];
        }

    } failure:^(NSError *error) {
//         NSLog(@"%@",error.description);
//        NSLog(@"%@",self.arr);
        [self saveText:self.arr];
        
    }];
    
}

#pragma mark ————————————— 保存沙盒 —————————————
-(void)saveText:(NSArray *)arr
{
    NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [docPaths lastObject];
    NSLog(@"documentsPath = %@", documentsPath);
    //构造字符串文件的存储路径
    NSString *strPath = [documentsPath stringByAppendingPathComponent:@"text.txt"];
    //通过将writeToFile:atomically:encoding:error:方法发送给字符串对象完成字符串存储到文件内的功能
    [arr writeToFile:strPath atomically:YES];
    [self.view addSubview:self.tableView];
   // 从文件中读取字符串对象
//    NSString *str = [NSString stringWithContentsOfFile:strPath encoding:NSUTF8StringEncoding error:nil];
}

/**
 iOS 原生数据请求
 @param url url
 @param dic 参数
 @param isPost 是否为POSt
 @param success 成功
 @param failure 失败
 */
-(void)httpByUrl:(NSString *)url
             dic:(NSDictionary *)dic
          isPost:(BOOL)isPost
         success:(void (^)(id responseObject))success
         failure:(void(^)(NSError *error))failure
{
    // 1、创建URL
    NSURL *urls = [NSURL URLWithString:url];
    
    // 2、创建请求对象
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:urls];
    
    if (isPost == YES)
    {
        [request setHTTPMethod:@"POST"];
        NSString *send = [self dealWithParam:dic];
        // 3、设置body
        NSData *bodyData = [send dataUsingEncoding:NSUTF8StringEncoding];
        [request setHTTPBody:bodyData];
    }
    else
    {
        [request setHTTPMethod:@"GET"];
    }
    // 4、创建会话
    NSURLSession *session = [NSURLSession sharedSession];
    // 5、创建数据请求任务
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *_Nullable data,NSURLResponse * _Nullable response,NSError * _Nullable error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (error)
            {
                failure(error);
            }
            else
            {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
                success(dic);
            }
        });
    }];
    
    // 6、启动任务
    [task resume];
    
}

// 处理字典参数
- (NSString *)dealWithParam:(NSDictionary *)param
{
    NSArray *allkeys = [param allKeys];
    
    NSMutableString *result = [NSMutableString string];
    
    for (NSString *key in allkeys)
    {
        
        NSString *str = [NSString stringWithFormat:@"%@=%@&",key,param[key]];
        
        [result appendString:str];
    }
    
    return [result substringWithRange:NSMakeRange(0, result.length-1)];
    
}
@end

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值