2016-08-23 6 views
1

Я хочу отображать свои изображения в виде сетки. Я использовал контроллер представления UICollection, данные, которые я передаю в формате JSON. can can can display images using JSON format. Может ли кто-нибудь найти мою ошибку? Вот мой кодPass Json Value to UICollection View

@interface ReceipeCollectionViewController() 
{ 
    NSMutableData *webdata; 
    NSURLConnection *connection; 
    NSMutableArray *contentarray; 
    NSMutableArray *array; 
} 

@end 

@implementation ReceipeCollectionViewController 

(void)viewDidLoad 
{ 
    [super viewDidLoad]; 
    [array removeAllObjects]; 
    [[self collectionView]setDelegate:self]; 
    [[self collectionView]setDataSource:self]; 
    array = [[NSMutableArray alloc] init];  
} 

(void)viewDidAppear:(BOOL)animated 
{ 
    NSString *[email protected]"http://wesotech.com/web/myrecipe/web_services/recipe_listing.php?"; 
    NSURL *url=[NSURL URLWithString:serverurl]; 
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
    connection = [NSURLConnection connectionWithRequest:request delegate:self]; 
    if(connection) 
    { 
     webdata=[[NSMutableData alloc]init]; 
    } 
    else 
    { 
     NSLog(@"Connection failure"); 
    } 
} 

(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [webdata appendData:data]; 
} 

(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    NSLog(@"Fail with error"); 
} 

(void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSError *error; 
    NSArray *results=[NSJSONSerialization JSONObjectWithData:webdata options:0 error:&error]; 
    [array removeAllObjects]; 
    [array addObjectsFromArray:results]; 
    [[self collectionView]reloadData]; 
} 

(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    [webdata setLength:0]; 
} 

(void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
} 

(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView 
{ 
    return 1; 
} 

(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section 
{ 
    return [array count]; 
} 

(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath 
{ 
    [self.mySpinner stopAnimating]; 

    static NSString *identifier = @"Cell"; 

    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath]; 

    UIImageView *recipeImageView = (UIImageView *)[cell.contentView viewWithTag:100]; 

    recipeImageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row] valueForKey:@"image"]]]]; 

    UITextField *recipeTitleView =(UITextField *)[cell.contentView viewWithTag:101]; 

    recipeTitleView.text=[[array objectAtIndex:indexPath.row]valueForKey:@"recname"]; 

    return cell; 
} 

@end 

Мой JSON Формат,

[ 

    {"image":"http:\/\/wesotech.com\/web\/myrecipe\/recipeimages\/2016080614704658059030.jpg","recname":"Italian Chicken","recid":"1"}, 
    {"image":"http:\/\/wesotech.com\/web\/myrecipe\/recipeimages\/2016080614704653421637.jpg","recname":"Fast Food Friday","recid":"2"}, 
    {"image":"http:\/\/wesotech.com\/web\/myrecipe\/recipeimages\/2016080614704648912893.jpg","recname":"Honey Clazed Lamb Chops","recid":"3"} 

] 
+0

Вы добавили следы или контрольные точки, чтобы проверить, если вы получите правильный URL, если загружен правильно изображение ...? Кроме того, ваш код не совсем показывает, где/как появляется 'UIImageView'. Вы также проверяли ограничения на это? Он может иметь правильное изображение, но просто имеет размер 0 или что-то подобное. Использование отладки просмотра предоставит больше информации. – jcaron

ответ

0

Вместо того, чтобы избежать ваш URL с \, используйте процентное кодирование в вашем JSON и декодировать его обратно в немаскированном строку, используя приведенный ниже код

NSString *imageUrl = @"http%3A%2F%2Fwesotech.com%2Fweb%2Fmyrecipe%2Frecipeimages%2F2016080614704658059030.jpg"; 
NSString *url = [imageUrl stringByRemovingPercentEncoding]; 

Еще один важный момент: Поскольку вы загружаете изображение с http://, вы должны установить Allow Arbitrary Loads в YES под App Transport Security Settings в вашем файле info.plist.

Также обратите внимание на то, что не рекомендуется устанавливать произвольные нагрузки, так как это приведет к проблемам безопасности. Было бы лучше, если бы вы могли бы иметь все в вашей сети требует использовать https://

+0

Просто знайте, что [Apple будет требовать подключения HTTPS для приложений iOS к концу 2016 года) (https://techcrunch.com/2016/06/14/apple-will-require-https-connections-for-ios-apps- by-the-end-of-2016 /) – Sudo

+0

Большое вам спасибо за его работу –

0

сделать класс tableViewCell и присвоить это имя класса для ячейки CollectionView в коммунальной сфере. Сделайте вывод изображения в классе TableViewCell и получите доступ к нему в методе делегата cellForItemAtIndexPath. Затем присвоить изображение с этим кодом:

[cell. recipeImageView sd_setImageWithURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row] valueForKey:@"image"]]]; 

Это, несомненно, поможет вам.