[novice learning IOS] tenth days - potatoes: potatoes client load API, filling a

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Long time no see, I have two days not publish articles about IOS, do not know if you have missed? Hey, I know a few people look at, but never mind, I will not be discouraged. I will write more to the future, I know that some say her in front of the I do not know the course, I will try my best, for sure.~

OK, now what I want to achieve the potatoes client. First screenshots, for everyone to share pictures.~

1/The picture


2 as I realized that a module, I'll say this one, then a supplement, okay? "

First, I define a custom cell, believe that everyone can see. I'll post code, then on a chart.

.h

//
//  LCCellController.h
//  North potato client
//
//  Created by lichan on 13-12-1.
//  Copyright (c) In 2013 com.lichan. All rights reserved.
//

#import <UIKit/UIKit.h>

#define kLabelTag 1

@interface LCCellController : UITableViewCell

@property (strong, nonatomic) IBOutlet UIImageView *imageView1;
@property (strong, nonatomic) IBOutlet UIImageView *imageView2;
@property (strong, nonatomic) IBOutlet UIImageView *imageView3;

@property (strong, nonatomic) IBOutlet UILabel *label1;

@property (strong, nonatomic) IBOutlet UILabel *label2;

@property (strong, nonatomic) IBOutlet UILabel *label3;


@end

Not what the content of a.M file, not put up

The Xib file. Although the use of the storeBoard, but I still used the Xib file a cell, you will not blame me.


2 and then have a look our channelViewController file. Although there are a lot of useless attributes, but I would have used it, don't worry.

If I don't, I just behind the notes a?.

//
//  LCChannelViewController.h
//  North potato client
//
//  Created by lichan on 13-11-30.
//  Copyright (c) In 2013 com.lichan. All rights reserved.
//

#import <UIKit/UIKit.h>


@interface LCChannelViewController : UIViewController<UITableViewDataSource,UITableViewDelegate,NSURLConnectionDataDelegate,NSURLConnectionDelegate>

@property UIView *channelView ;
@property (strong, nonatomic) IBOutlet UILabel *channelTextShow;

@property (weak, nonatomic) IBOutlet UITableView *myTableView;

@property(strong,nonatomic)NSMutableData *unHandleData; //Receive data
@property(strong,nonatomic)NSMutableData *handledData;//?


@property (strong,nonatomic)NSMutableDictionary *objectsDic;//?

@property (strong,nonatomic)NSMutableDictionary *handledDataDic;//The DIC data transformation from data to JSON

@property (strong,nonatomic)NSMutableArray *resultDataArr;
@property (strong,nonatomic)NSMutableArray *pageDataArr;


@property (strong,nonatomic)NSMutableArray *unHandleDataArr;//?

@property (strong,nonatomic)NSMutableArray *handleDataArr;//?

@property UIButton *moiveButton,*musicButton,*hotButton,*cartoonButton,*tvplayButton,*varShowButton;


-(void)createChannelView;

- (IBAction)channelPressed:(id)sender;





@end

It has four protocols, including tableViewDelegate, dataDelegate, ConnectionDelegate, ConnectionDataDelegate. of the four protocols are must implement the agreement. We will realize the detail in the.M file.

The ch.m file, there may be some chaos, the use of some interface is very much, but I have a good piece.~~

//
//  LCChannelViewController.m
//  North potato client
//
//  Created by lichan on 13-11-30.
//  Copyright (c) In 2013 com.lichan. All rights reserved.
//

#import "LCChannelViewController.h"

#import "LCCellController.h"




#define kCellRowObject 3

#define kCellColumn 1

@interface LCChannelViewController ()

@end

@implementation LCChannelViewController

@synthesize myTableView;

@synthesize channelView,channelTextShow;
@synthesize  moiveButton,musicButton,hotButton,cartoonButton,tvplayButton,varShowButton;

@synthesize unHandleDataArr,handleDataArr;

@synthesize objectsDic,handledDataDic;//The dictionary definition of receiving data

@synthesize resultDataArr,pageDataArr;
//You can combine images and text, to achieve tableview

-(void)createChannelView//Can realize more about slide up and down ~ ~ ~ Displays
{//This is when you click the triangle symbols appear small menu, we created 6 button. each added selector,
    if (channelView == nil) {
        channelView = [[UIView alloc]initWithFrame:CGRectMake(0, 57, 320, 100)];
        channelView.backgroundColor = [UIColor grayColor];
    
        moiveButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 80,40 )];
        [moiveButton  setTitle:@"Film" forState:UIControlStateNormal];
        [moiveButton setTag:22];
        [moiveButton addTarget:self action:@selector(channelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        
                       
       musicButton = [[UIButton alloc]initWithFrame:CGRectMake(100, 0, 80, 40)];
         [musicButton  setTitle:@"Music" forState:UIControlStateNormal];
        [musicButton setTag:14];
        [musicButton addTarget:self action:@selector(channelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
       
        hotButton = [[UIButton alloc]initWithFrame:CGRectMake(200, 0, 80, 40)];
         [hotButton  setTitle:@"Hot spot" forState:UIControlStateNormal];
        [hotButton setTag:29];
        [hotButton addTarget:self action:@selector(channelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        
        cartoonButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 50, 80, 40)];
         [cartoonButton  setTitle:@"Animation" forState:UIControlStateNormal];
        [cartoonButton setTag:9];
        [cartoonButton addTarget:self action:@selector(channelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        
        tvplayButton = [[UIButton alloc]initWithFrame:CGRectMake(100, 50, 80, 40)];
          [tvplayButton  setTitle:@"TV drama" forState:UIControlStateNormal];
        [tvplayButton setTag:30];
        [tvplayButton addTarget:self action:@selector(channelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        
        varShowButton = [[UIButton alloc]initWithFrame:CGRectMake(200, 50, 80, 40)];
          [varShowButton  setTitle:@"Variety" forState:UIControlStateNormal];
        [varShowButton setTag:31];
        [varShowButton addTarget:self action:@selector(channelButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        
        [channelView addSubview:moiveButton];
        [channelView addSubview:musicButton];
        [channelView addSubview:hotButton];
        [channelView addSubview:cartoonButton];
        [channelView addSubview:tvplayButton];
        [channelView addSubview:varShowButton];
    }
        [self.view addSubview:channelView];//The menu to the view, but to set hidden.
        

}



   //channleButton!!//
-(void)channelButtonPressed:(id)sender
{
    self.channelView.hidden = YES;
    
    int buttonTag = [sender tag];
    
    UIButton *button = (UIButton *)[sender viewWithTag:buttonTag];
    
    channelTextShow.text = button.titleLabel.text;
    
    [self createConnectionByChannelID:buttonTag];
    NSLog(@"Click the%d",buttonTag);
 

}

//Click on the button or label display. Button! Bug! / here is the first use, you must click two times, I haven't found the cause, can help me have a look.
- (IBAction)channelPressed:(id)sender {
    //pressTime++;
     [self createChannelView];
    
    NSLog(@"hidden:%d",self.channelView.hidden);
    
    if (self.channelView.hidden == YES)
    {
          self.channelView.hidden = NO;
        NSLog(@"no");
        return;
    }
    
    else
    {
        self.channelView.hidden = YES;
        NSLog(@"yes");
        return;
        
    }

    
}



- (void)viewDidLoad
{
    [super viewDidLoad];
    //If we do not judge this sentence, so we start the first data bit nil, then our tableview is blank, so terrible oh
    if (resultDataArr == nil) {
            NSArray *pathDocs = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSAllDomainsMask, YES);
            NSString *path = [[pathDocs objectAtIndex:0] stringByAppendingString:@"result"];//Storage path and name data
        
            self.resultDataArr = [NSMutableArray arrayWithContentsOfFile:path];
    }
    self.channelView.hidden = YES;//I found that I initiated a hidden, but when it came to judge, or no, really worried~

    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
     [self createConnectionByChannelID:10];
    
  //self.handleDataArr = [[NSMutableArray alloc]initWithObjects:@"1",@"11",@"111",@"12",@"122",@"1222",@"13",@"133",@"1333",@"14",@"144",@"1444",@"15",nil];
    
    	// Do any additional setup after loading the view.
}

//----------------------------------------------------------

//Tableview date delegate protocol
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    NSInteger  col = (NSInteger) [self.resultDataArr count]/kCellRowObject;
   return  col;
   
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return kCellColumn;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIndentifier = @"cellIndentifiter";
    
    static BOOL nibsRegistered = NO;
    if (!nibsRegistered) {
        
        UINib *nib = [UINib nibWithNibName:@"LCCell" bundle:nil];
        
        [tableView registerNib:nib forCellReuseIdentifier:CellIndentifier];
        nibsRegistered = YES;
     
    }
    
    LCCellController *cell = [tableView dequeueReusableCellWithIdentifier:CellIndentifier];
    
    NSInteger row = [indexPath row];
    

    for (int i = 0; i <kCellRowObject; i++) {
        
        
     //Implementation of multi thread load data
        self.objectsDic = [self.resultDataArr objectAtIndex:row *3 +i ];
        NSString *objectTitle = [objectsDic objectForKey:@"title"];
        if(i+1 == 1)
        {
            cell.label1.text = objectTitle;
          
        }
        else if(i+1 == 2)
        {
            cell.label2.text = objectTitle;
        
        }
        else if(i+1 == 3)
        {
            cell.label3.text = objectTitle;
        
        }
       

        //Image loading
          NSString *picUrlString = [objectsDic objectForKey:@"picUrl"];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
          
            __block UIImage *infoimage;//In order to preserve the value of blcok processing
          
            dispatch_group_t group = dispatch_group_create();
            //Multi thread 1, realize image loading
            dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
                NSData *imageData = [self loadImageAndMovieInfoByURL:picUrlString];
                infoimage = [UIImage imageWithData:imageData scale:1.14];
                
                
                
            });
            //Multi threaded 2: achieve label load
            dispatch_group_async(group, dispatch_get_global_queue(0, 0), ^{
              
            });
            //The follow-up can add more thread of multi thread downloading efficiency
    
            //
            //The only other process is executed to perform the block.// will temporarily be empty
            dispatch_group_notify(group, dispatch_get_global_queue(0, 0), ^{
            
                dispatch_sync(dispatch_get_main_queue(), ^{
                    if(i+1 == 1)
                    {
                        cell.imageView1.image = infoimage;
                        
                    }
                    else if(i+1 == 2)
                    {
                        cell.imageView2.image = infoimage;
                       
                    }
                    else if(i+1 == 3)
                    {
                        cell.imageView3.image = infoimage;
                       
                    }
                    
               
                //Return to the main thread
                    
                });
        //
            
            });

        });
        
    }
    

    return cell;
}

//Multi thread loading on the picture and the label information
-(NSData *)loadImageAndMovieInfoByURL:(NSString *)urlString
{
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
    
    NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    return data;
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 104.0;
}
//-------------------------- file write ------------------------

//File write interface
-(void)saveReceivedDataToFileByFileName:(NSString *)fileName WithData:(id)data  //???? What kind of file write?
{
    NSArray *pathDocs = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSAllDomainsMask, YES);
    NSString *path = [[pathDocs objectAtIndex:0] stringByAppendingString:[NSString stringWithFormat:@"%@",fileName]];//Storage path and name data
    
    
    [data writeToFile:path atomically:YES];
    
    
    
}




//------------------------- connection --------------------------
//    Create the interface, realize the connection request
-(void)createConnectionByChannelID:(NSInteger)channelID
{
    NSString *param = [[NSString alloc]initWithFormat:@"app_key=59337596b4aeb64c&format=json&channelId=%d&pageNo=1&pageSize=20&orderBy=t",channelID];
    
    
    NSURL *url = [NSURL URLWithString:@" ;];
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
    
    [request setHTTPMethod:@"POST"];
    
    [request setHTTPBody:[param dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSURLConnection *conn=[NSURLConnection connectionWithRequest:request delegate:self];
    
    if (conn)
        NSLog(@"A successful connection");
    else
        NSLog(@"Connection failed");
    
    
}

//Implementation of connection protocol
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"The data type returned is the situation%@",[response textEncodingName]);
    
    self.unHandleData = [NSMutableData dataWithCapacity:20];
    //Rated capacity.
    
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"To receive data, the packet size:%d",[data length]);
    [self.unHandleData appendData:data];
  

}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [self saveReceivedDataToFileByFileName:@"channle.JSON" WithData:self.unHandleData];
    
    [self jsonDataParse];

}
//Use original appleAPI. return an array of video information
-(void) jsonDataParse
{
    NSError *error;
    self.handledDataDic = [NSJSONSerialization JSONObjectWithData:self.unHandleData options:NSJSONWritingPrettyPrinted error:&error];
    if (error != nil) {
        NSLog(@"%@",error);
    }
    
    self.resultDataArr = [self.handledDataDic objectForKey:@"results"];

    
    [self saveReceivedDataToFileByFileName:@"result" WithData:self.resultDataArr];
    NSLog(@"=========Data storage has been completed");
    
    self.pageDataArr   = [self.handledDataDic objectForKey:@"page"   ];
    
    [self.myTableView reloadData];//Reload the data.
    NSLog(@"Reload the data");

}
//-----------------------------------------

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

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}


@end
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Virgil at December 14, 2013 - 1:59 PM