http://api.testmy.co/user/files
我需要获取数据并在我的表格视图中显示该数据,如
grid view
。我对这种类型的处理 API、获取请求等很陌生。如果有人可以解释一下这个"Get type request"
以及如何在我的表格视图(如网格视图)中显示数据。我只有这个 URL 要做(例如只有上面的 URL)。
任何人都可以帮助我提供一些教程或 git-hub 或任何有关它的想法吗?
我帮助您获取响应。将响应数据保存到数组或字典后,您可以显示到表格视图。
-(void)getResponse
{
//just give your URL instead of my URL
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://api.worldweatheronline.com/free/v1/search.ashx?query=London&num_of_results=3&format=json&key=xkq544hkar4m69qujdgujn7w"]];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/json;charset=UTF-8" forHTTPHeaderField:@"content-type"];
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
//You need to check response.Once you get the response copy that and paste in ONLINE JSON VIEWER.If you do this clearly you can get the correct results.
//After that it depends upon the json format whether it is DICTIONARY or ARRAY
//If it(RESPONSE) starts with dictionary({...}),you need to write coding blow like this
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
NSArray *array=[[jsonDict objectForKey:@"search_api"]objectForKey:@"result"];
//But if it(RESPONSE) starts with array([...]),you need to write coding blow like this
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:responseData options: NSJSONReadingMutableContainers error: &err];
}
如果你想获得网格视图,你最好使用CollectionView。
- (void)viewDidLoad
{
[super viewDidLoad];
[self getResponse];
UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
//Register the custom cell for collection view
UINib *cellNib = [UINib nibWithNibName:@"CustomCell" bundle:nil];
[collectionViewHorizontalVertical registerNib:cellNib forCellWithReuseIdentifier:@"cvCell"];
}
//Collection View Delegates method
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return jsonArray.count;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"cvCell";
CustomCell *cell = (CustomCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIdentifier forIndexPath:indexPath];
cell.imgViewCollection.image = [UIImage imageNamed:[jsonArray objectAtIndex:indexPath.row]];
return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(200, 200); //Please give your required size
}