所以我用我的 JSON 与 UICollectionView 一起工作。我编写此代码进行解析,但我不明白为什么它不起作用。我的 JSON 有([jsontest2] 在键“imageMain”之后)。
所以我粘贴我的代码,请帮助我:
@property (nonatomic,strong) NSMutableArray *patternImagesArray;
@end
@implementation ViewController
@synthesize patternImagesArray = _patternImagesArray;
NSURLConnection *connection;
NSMutableData *webdata;
尝试从 JSON 获取数据:
-(void) viewDidLoad{
_patternImagesArray = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:@"site"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webdata = [[NSMutableData alloc]init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webdata setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webdata appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
JSON解析:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webdata options:0 error:nil];
NSArray *tmp =[allDataDictionary objectForKey:@"jsontest2"];
if (tmp.count>0){
for (NSDictionary *diction in tmp) {
[self.patternImagesArray addObject:diction];
}
NSLog(@"%@", self.patternImagesArray);
}
[self.collectionView reloadData];
}
一些自定义的东西:
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
PatternView *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PatternCell" forIndexPath:indexPath];
NSString *myPatternString = [[self.patternImagesArray objectAtIndex:indexPath.row] valueForKey:@"thumb"];
NSLog(@"myPatternString %@",myPatternString);
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:myPatternString]];
cell.patternImageView.image = [UIImage imageWithData:data];
return cell;
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
return [self.patternImagesArray count];
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
return CGSizeMake(100.0, 100.0);
}