Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone



Clound SSD Virtual Server

iOS/iPhone Collection View (UICollectionView) and JSON (Web Server URL)

iOS/iPhone Collection View (UICollectionView) and JSON (Web Server URL) หลังจากที่ได้เขียน iOS กับ JSON ที่อ่านข้อมูลจาก URL (Website) มาได้ซะ 4-5 บทความ จะเกิด idea ที่จะสามารถต่อยอดใช้กับ Application ได้มากมาย และในตัวอย่างนี้จะได้ Apply ใช้กับ Collection View ที่แสดงรูปภาพเป็นแบบ Column ถ้าจะมองในมุมมองของการเขียน App น่าจะเป็นการสร้าง อัลบั้ม Gallery แบบ Online โดยเราสามารถจัดการกับข้อมูลทุกอย่างอยู่บน Web Server ด้วย PHP กับ MySQL Database และจะสร้างช่องทางสำหรับ iOS ที่จะอ่านข้อมูลเหล่านั้น โดยใช้ JSON สำหรับการแลกเปลี่ยนข้อมูล เรามาดูตัวอย่างการทำแบบง่าย ๆ

iOS/iPhone Collection View (UICollectionView) and JSON (Web Server URL)

iOS/iPhone Collection View (UICollectionView) and JSON (Web Server URL)


สำหรับ Collection View จะเป็นบทความที่เขียนต่อจากบทความก่อนหน้านี้ ซึ่งจะใช้ NSMutableArray และ NSDictionary แบบกำหนดไปใน Code ของ Objective-C เข้ามาจัดการกับข้อมูล ที่ใช้สำหรับการแสดงผลบน Collection View และบทความนี้จะเปลี่ยนจากการ Fix Code มาเป็นการอ่านข้อมูลจาก URL (Website) ซึ่งอยู่ใน Web Server ทำงานด้วย PHP และ MySQL Database โดยใช้การรับ-ส่งข้อมูลในรูปแบบของ JSON

iOS/iPhone Collection View (UICollectionViewController) Multiple Column Item (iPhone, iPad)

iOS/iPhone Collection View and Master Detail (Objective-C, iPhone, iPad)

ดังนั้นเพื่อความเข้าใจควรอ่าน 2 บทความนี้ก่อน และได้เข้าใจและ สามารถที่จะ Apply ได้อย่างถูกต้อง และสำหรับ JSON สามารถอ่านได้จาก บทความนี้

OS/iPhone and JSON (Create JSON and JSON Parsing, Objective-C)


Web Server โครงสร้างไฟล์ PHP และ MySQL Database บน Web Server

MySQL Database
CREATE TABLE `images` (
  `ImageID` int(3) NOT NULL auto_increment,
  `Name` varchar(50) NOT NULL,
  `Path` varchar(100) NOT NULL,
  PRIMARY KEY  (`ImageID`)
) ENGINE=MyISAM AUTO_INCREMENT=10 ;

-- 
-- Dumping data for table `images`
-- 

INSERT INTO `images` VALUES (1, 'Image 1', 'https://www.thaicreate.com/url/img1.png');
INSERT INTO `images` VALUES (2, 'Image 2', 'https://www.thaicreate.com/url/img2.png');
INSERT INTO `images` VALUES (3, 'Image 3', 'https://www.thaicreate.com/url/img3.png');
INSERT INTO `images` VALUES (4, 'Image 4', 'https://www.thaicreate.com/url/img4.png');
INSERT INTO `images` VALUES (5, 'Image 5', 'https://www.thaicreate.com/url/img5.png');
INSERT INTO `images` VALUES (6, 'Image 6', 'https://www.thaicreate.com/url/img6.png');
INSERT INTO `images` VALUES (7, 'Image 7', 'https://www.thaicreate.com/url/img7.png');
INSERT INTO `images` VALUES (8, 'Image 8', 'https://www.thaicreate.com/url/img8.png');
INSERT INTO `images` VALUES (9, 'Image 9', 'https://www.thaicreate.com/url/img9.png');

โครงสร้างของ MySQL Database ที่อยู่บน Web Server

iOS/iPhone Collection View (UICollectionView) and JSON (Web Server URL)

getImages.php ไฟล์ PHP สำหรับแสดง JSON ที่อ่านข้อมูลมาจาก MySQL Database
<?php
	$objConnect = mysql_connect("localhost","root","root");
	$objDB = mysql_select_db("mydatabase");
	$strSQL = "SELECT * FROM images WHERE 1  ";
	$objQuery = mysql_query($strSQL);
	$intNumField = mysql_num_fields($objQuery);
	$resultArray = array();
	while($obResult = mysql_fetch_array($objQuery))
	{
		$arrCol = array();
		for($i=0;$i<$intNumField;$i++)
		{
			$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
		}
		array_push($resultArray,$arrCol);
	}
	
	mysql_close($objConnect);
	
	echo json_encode($resultArray);
?>

ทดสอบเรียก PHP ผ่าน Web Browser








iOS/iPhone Collection View (UICollectionView) and JSON (Web Server URL)

ไฟล์ JSON เมื่อทดสอบเรียกจาก Web Server ที่ได้จาก PHP และ MySQL Database และจะสังเกตุว่าใน JSON จะมี URL ของรูปภาพด้วย

iOS/iPhone Collection View (UICollectionView) and JSON (Web Server URL)

ทดสอบเรียก URL ของ รูปภาพ และจากข้อมูลดังรูป เราจะสามารถเขียน Code ของ Objective-C สำหรับการอ่าน JSON และแปลงข้อมูลให้อยู่ในรูปแบบของ NSMutableArray และ NSDictionary ที่จะแสดงบน Collection View ได้ดังนี้

    NSMutableArray *myObject;
    
    // A dictionary object
    NSDictionary *dict;
    
    // Define keys
    NSString *imageid;
    NSString *name;
    NSString *path;

        // Define keys
    imageid = @"ImageID";
    name = @"Name";
    path = @"Path";
    
    // Create array to hold dictionaries
    myObject = [[NSMutableArray alloc] init];
    
    NSData *jsonData = [NSData dataWithContentsOfURL:
                        [NSURL URLWithString:@"https://www.thaicreate.com/url/getImages.php"]];
    
    id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    
    // values in foreach loop
    for (NSDictionary *dataDict in jsonObjects) {
        NSString *strImageID = [dataDict objectForKey:@"ImageID"];
        NSString *strName = [dataDict objectForKey:@"Name"];
        NSString *strPath = [dataDict objectForKey:@"Path"];
        
        dict = [NSDictionary dictionaryWithObjectsAndKeys:
                strImageID, imageid,
                strName, name,
                strPath, path,
                nil];
        [myObject addObject:dict];
    }


กลับมายัง Project ที่อยู่บน Xcode ซึ่งจาก 2 บทความที่ได้แจ้งไว้ก่อนหน้านี้ เราได้หน้าจอ View ขึ้นมา 2 View ซึ่งอยู่บน Storyboard และควบคุมการทำงานด้วย Navigation Controller

iOS/iPhone Collection View (UICollectionView) and JSON (Web Server URL)

หน้าจอ View ที่อยู่บน Storyboard ซึ่งจากตัวอย่างก่อนหน้านี้เราจะเขียน Code ใน Class ของภาษา Objective-C ทั้งหมด 6 ไฟล์ดังนี้

MasterViewController.h
//
//  MasterViewController.h
//  CollectionViewApp
//
//  Created by Weerachai on 11/3/55 BE.
//  Copyright (c) 2555 Weerachai. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface MasterViewController : UICollectionViewController

@end


MasterViewController.m
//
//  MasterViewController.m
//  CollectionViewApp
//
//  Created by Weerachai on 11/3/55 BE.
//  Copyright (c) 2555 Weerachai. All rights reserved.
//

#import "MasterViewController.h"
#import "CustomColumnCell.h"
#import "DetailViewController.h"

@interface MasterViewController ()
{
    NSMutableArray *myObject;
    
    // A dictionary object
    NSDictionary *dict;
    
    // Define keys
    NSString *imageid;
    NSString *name;
    NSString *path;
}

@end

@implementation MasterViewController

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

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    // Define keys
    imageid = @"ImageID";
    name = @"Name";
    path = @"Path";
    
    // Create array to hold dictionaries
    myObject = [[NSMutableArray alloc] init];
    
    NSData *jsonData = [NSData dataWithContentsOfURL:
                        [NSURL URLWithString:@"https://www.thaicreate.com/url/getImages.php"]];
    
    id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    
    // values in foreach loop
    for (NSDictionary *dataDict in jsonObjects) {
        NSString *strImageID = [dataDict objectForKey:@"ImageID"];
        NSString *strName = [dataDict objectForKey:@"Name"];
        NSString *strPath = [dataDict objectForKey:@"Path"];
        
        dict = [NSDictionary dictionaryWithObjectsAndKeys:
                strImageID, imageid,
                strName, name,
                strPath, path,
                nil];
        [myObject addObject:dict];
    }
    
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return myObject.count;
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                 cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    CustomColumnCell *myCell = [collectionView
                                dequeueReusableCellWithReuseIdentifier:@"myCell"
                                forIndexPath:indexPath];
    
    NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
    
    NSURL *url = [NSURL URLWithString:[tmpDict objectForKey:path]];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *img = [[UIImage alloc] initWithData:data];
    
    myCell.displayImage.image = img;
    myCell.displayDetail.text= [tmpDict objectForKey:name];

    return myCell;
    
}


- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    
    if ([[segue identifier] isEqualToString:@"showDetail"]) {
        
        NSIndexPath *IndexPath = [[self.collectionView indexPathsForSelectedItems] objectAtIndex:0];
        NSDictionary *tmpDict = [myObject objectAtIndex:IndexPath.row];

        [[segue destinationViewController] setImageItem:[tmpDict objectForKey:path]];
        [[segue destinationViewController] setDetailItem:[tmpDict objectForKey:name]];

    }
    
}

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

@end









CustomColumnCell.h
//
//  CustomColumnCell.h
//  CollectionViewApp
//
//  Created by Weerachai on 11/3/55 BE.
//  Copyright (c) 2555 Weerachai. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface CustomColumnCell : UICollectionViewCell

@property (nonatomic, strong) IBOutlet UIImageView *displayImage;
@property (nonatomic, strong) IBOutlet UILabel *displayDetail;

@end


CustomColumnCell.m
//
//  CustomColumnCell.m
//  CollectionViewApp
//
//  Created by Weerachai on 11/3/55 BE.
//  Copyright (c) 2555 Weerachai. All rights reserved.
//

#import "CustomColumnCell.h"

@implementation CustomColumnCell

@synthesize displayImage = _displayImage;
@synthesize displayDetail = _displayDetail;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

@end


DetailViewController.h
//
//  DetailViewController.h
//  CollectionViewApp
//
//  Created by Weerachai on 11/3/55 BE.
//  Copyright (c) 2555 Weerachai. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface DetailViewController : UIViewController
{
    IBOutlet UIImageView *imgViewImage;
    IBOutlet UILabel *lblViewDetail;
}

@property (strong, nonatomic) id sImage;
@property (strong, nonatomic) id sDetail;

-(void) setImageItem:(id) newImage;
-(void) setDetailItem:(id) newDetail;

@end


DetailViewController.m
//
//  DetailViewController.m
//  CollectionViewApp
//
//  Created by Weerachai on 11/3/55 BE.
//  Copyright (c) 2555 Weerachai. All rights reserved.
//

#import "DetailViewController.h"

@interface DetailViewController ()

@end

@implementation DetailViewController

@synthesize sImage;
@synthesize sDetail;

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

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    NSURL *url = [NSURL URLWithString:[sImage description]];
    NSData *data = [NSData dataWithContentsOfURL:url];
    UIImage *img = [[UIImage alloc] initWithData:data];

    imgViewImage.image = img;
    
    lblViewDetail.text = [sDetail description];
}

- (void)setImageItem:(id)newImage
{
    sImage = newImage;
}

- (void)setDetailItem:(id)newDetail
{
    sDetail = newDetail;
}


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

- (void)dealloc {
    [imgViewImage release];
    [lblViewDetail release];
    [super dealloc];
}
@end




Screenshot

iOS/iPhone Collection View (UICollectionView) and JSON (Web Server URL)

แสดง Image บน Collection View ที่อ่านข้อมูลมาจาก JSON ที่อยู่บน Web Server

iOS/iPhone Collection View (UICollectionView) and JSON (Web Server URL)

เมื่อคลิกแต่ล่ะ Item ของ Collection View

   
Share


ช่วยกันสนับสนุนรักษาเว็บไซต์ความรู้แห่งนี้ไว้ด้วยการสนับสนุน Source Code 2.0 ของทีมงานไทยครีเอท


ลองใช้ค้นหาข้อมูล


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2012-12-06 10:36:07 / 2017-03-26 09:02:10
  Download : Download  iOS/iPhone Collection View (UICollectionView) and JSON (Web Server URL)
 Sponsored Links / Related

 
iOS/iPhone and JSON (Create JSON and JSON Parsing, Objective-C)
Rating :

 
iOS/iPhone Table View and JSON (UITableView from JSON Parser)
Rating :

 
iOS/iPhone Passing JSON (NSJSONSerialization) Between View
Rating :

 
iOS/iPhone PHP/MySQL and JSON Parsing (Objective-C)
Rating :

 
iOS/iPhone Display Image on Table View from JSON URL (Web Site)
Rating :

 
iOS/iPhone Search Bar (UISearchBar) Data from Web Server Using JSON
Rating :

 
iOS/iPhone Picker View and JSON (UIPickerView)
Rating :

 
iOS/iPhone XML Parser / XML Feed from URL (NSXMLParser ,Objective-C)
Rating :

 
iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)
Rating :


ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 04
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่