我正在 ios 中制作一个有 4 个屏幕的应用程序,其中一个我想用作照片库。我使用图形从 facebook 页面下载的这些图像。在我的 ViewController 类中的 viewDidLoad 方法中创建连接 url:
(void)viewDidLoad
{
[super viewDidLoad];
NSString *urlString = [NSString stringWithFormat:@"https://graph.facebook.com/NBAStoreNYC/photos"];
NSURL *url = [NSURL URLWithString:urlString];
// Create NSURLRequest
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30];
//Create conection
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
if (connection)
{
NSLog(@"Connecting...");
dataJSON = [[NSMutableData alloc] init];
}
else
{
NSLog(@"ERROR: Unable to create connection.");
}
}
为了下载图像,我解析了返回的 JSON,以便在每个 for..end 中获取图像的 URL:
-(void)connection:(NSURLConnection )connection didFailWithError:(NSError )error{ NSLog(@"Error: %@", [error localizedDescription]); }
-(void)connection:(NSURLConnection )connection didReceiveResponse:(NSURLResponse )response{ NSLog(@"Received response: %@", response); [dataJSON setLength:0]; }
-(void)connection:(NSURLConnection )connection didReceiveData:(NSData )data { [dataJSON appendData:data]; }
-(void) connectionDidFinishLoading:(NSURLConnection *) connection {
NSError *error;
UIImageView *image1;
NSMutableArray *coleccion=[[NSMutableArray alloc] init];
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:dataJSON options:kNilOptions error:&error];
NSArray *data = [dic objectForKey:@"data"];
if (!dic) {
NSLog(@"Error parsing JSON");
} else {
for(NSDictionary *item in [dic objectForKey:@"data"]) {
for(NSDictionary *attachment in [item objectForKey:@"images"]) {
NSString *nombre = [attachment objectForKey:@"source"];
NSURL * imageURL = [NSURL URLWithString:nombre];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
image1 = [UIImage imageWithData:imageData];
[items addObject:image1];
}
}
}
//[self.view setNeedsDisplay];
}
最后我用收藏视图创建了我的画廊:
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
return [items count]*5;
}
-(UICollectionViewCell )collectionView:(UICollectionView )collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = @"CollectionCell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *imageView = (UIImageView *)[cell viewWithTag:1];
imageView.image = [items objectAtIndex:indexPath.row%1];
return cell;
}
现在,当我运行应用程序时没有加载任何图像,为什么?我如何解决它以显示图像?练习几乎等于:http ://www.techotopia.com/index.php/An_iPhone_iOS_6_Storyboard-based_Collection_View_Tutorial 不同之处在于我想下载 facebook 图形的图像,而不是已经将它们加载到项目中
非常感谢你。