iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)
iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)
iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView) บทความนี้จะเป็นการ Apply ใช้NSURLConnection กับการเชื่อมต่อข้อมูลของ MySQL Database ที่ถูกจัดเก็บไว้บน Web Server โดยใช้ php ทำหน้าที่ในการอ่านข้อมูลจาก MySQL แล้งแปลงเป็น JSON เพื่อจะรอ Client เข้าไปทำการ Request ข้อมูลผ่าน URL (Webiste) ที่มีนามสกุล .php โดยในตัวอย่างนี้เราจะได้เรียนรู้และ Apply การใช้งานอยู่ 3-4 ตัวเช่น NSURLConnection , PHP MySQL และการใช้ JSON Parser และการนำข้อมูลเหล่านั้นแสดงผลบน Table View (UITableView)

iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)
และเพื่อความเข้าใจในบทความนี้ อยากจะแนะนำให้อ่านบทความต่าง ๆ เหล่านี้ที่เกี่ยวข้อง เช่น NSURLConnection , JSONParser , และ Table View แต่ถ้าเข้าใจแล้วก็สามารถข้ามบทความเหล่านั้นได้เลย
iOS/iPhone NSURLConnection (Objective-C)
iOS/iPhone and JSON (Create JSON and JSON Parsing , Objective-C)
iOS/iPhone Display Image on Table View from JSON URL (Web Site)
Example ตัวอย่างการใช้ NSURLConnection และ PHP MySQL / JSON (TableView,UITableView)
MySQL Database
โครงสร้างของ MySQL Database

getGallery.php
ไฟล์ php สำหรับอ่านข้อมูลจาก MySQL และแปลงให้เป็น JSON

เมื่อเรียกไฟล์ php ผ่าน URL ของ Web Browser
ตัวอย่างนี้จะแสดงรูปภาพด้วย และทดสอบการเรียกรูปภาพผ่าน Web Browser
เริ่มต้นด้วยการสร้าง Application บน Xcode แบบ Single View Application
เลือกและไม่เลือกรายการดังรูป
ตอนนี้หน้าจอ View จะยังว่าง ๆ
ลาก Table View (UITableView) มาวางไว้บนหน้าจอ
คลิกขวาที่ Table View ให้ทำการเชื่อม dataSource และ delegate กับ File's Owner
ใน Class ของ .h ให้เชื่อม IBOutlet ให้เรียบร้อย จากนั้นให้เขียน Code ของ Objective-C ทั้งหมดดังนี้
ViewController.h
ViewController.m
Screenshot
แสดงข้อมูลบน Table View ซึ่งอ่านมาจาก URL ทำงานด้วย PHP กับ MySQL ผ่าน Class ของ NSURLConnection
CD:http://www.thaicreate.com/mobile/ios-iphone-nsurlconnection-php-mysql-json.html

iOS/iPhone NSURLConnection and PHP MySQL / JSON (TableView,UITableView)
และเพื่อความเข้าใจในบทความนี้ อยากจะแนะนำให้อ่านบทความต่าง ๆ เหล่านี้ที่เกี่ยวข้อง เช่น NSURLConnection , JSONParser , และ Table View แต่ถ้าเข้าใจแล้วก็สามารถข้ามบทความเหล่านั้นได้เลย
iOS/iPhone NSURLConnection (Objective-C)
iOS/iPhone and JSON (Create JSON and JSON Parsing , Objective-C)
iOS/iPhone Display Image on Table View from JSON URL (Web Site)
Example ตัวอย่างการใช้ NSURLConnection และ PHP MySQL / JSON (TableView,UITableView)
MySQL Database
01.
CREATE
TABLE
`gallery` (
02.
`GalleryID`
int
(3)
NOT
NULL
auto_increment,
03.
`
Name
`
varchar
(50)
NOT
NULL
,
04.
`TitleName`
varchar
(150)
NOT
NULL
,
05.
`Thumbnail`
varchar
(100)
NOT
NULL
,
06.
PRIMARY
KEY
(`GalleryID`)
07.
) ENGINE=MyISAM AUTO_INCREMENT=5 ;
08.
09.
--
10.
-- Dumping data for table `gallery`
11.
--
12.
13.
INSERT
INTO
`gallery`
VALUES
(1,
'Name 1'
,
'The my gallery title 1'
,
'http://www.thaicreate.com/url/girl1.jpg'
);
14.
INSERT
INTO
`gallery`
VALUES
(2,
'Name 2'
,
'The my gallery title 2'
,
'http://www.thaicreate.com/url/girl2.jpg'
);
15.
INSERT
INTO
`gallery`
VALUES
(3,
'Name 3'
,
'The my gallery title 3'
,
'http://www.thaicreate.com/url/girl3.jpg'
);
16.
INSERT
INTO
`gallery`
VALUES
(4,
'Name 4'
,
'The my gallery title 4'
,
'http://www.thaicreate.com/url/girl4.jpg'
);

getGallery.php
01.
<?
02.
$objConnect
= mysql_connect(
"localhost"
,
"root"
,
"root"
);
03.
$objDB
= mysql_select_db(
"mydatabase"
);
04.
$strSQL
=
"SELECT * FROM gallery WHERE 1 "
;
05.
$objQuery
= mysql_query(
$strSQL
);
06.
$intNumField
= mysql_num_fields(
$objQuery
);
07.
$resultArray
=
array
();
08.
while
(
$obResult
= mysql_fetch_array(
$objQuery
))
09.
{
10.
$arrCol
=
array
();
11.
for
(
$i
=0;
$i
<
$intNumField
;
$i
++)
12.
{
13.
$arrCol
[mysql_field_name(
$objQuery
,
$i
)] =
$obResult
[
$i
];
14.
}
15.
array_push
(
$resultArray
,
$arrCol
);
16.
}
17.
18.
mysql_close(
$objConnect
);
19.
20.
echo
json_encode(
$resultArray
);
21.
?>

เมื่อเรียกไฟล์ php ผ่าน URL ของ Web Browser

ตัวอย่างนี้จะแสดงรูปภาพด้วย และทดสอบการเรียกรูปภาพผ่าน Web Browser

เริ่มต้นด้วยการสร้าง Application บน Xcode แบบ Single View Application

เลือกและไม่เลือกรายการดังรูป

ตอนนี้หน้าจอ View จะยังว่าง ๆ

ลาก Table View (UITableView) มาวางไว้บนหน้าจอ

คลิกขวาที่ Table View ให้ทำการเชื่อม dataSource และ delegate กับ File's Owner

ใน Class ของ .h ให้เชื่อม IBOutlet ให้เรียบร้อย จากนั้นให้เขียน Code ของ Objective-C ทั้งหมดดังนี้
ViewController.h
01.
//
02.
// ViewController.h
03.
// NSURLConnectioJSON
04.
//
05.
// Created by Weerachai on 12/8/55 BE.
06.
// Copyright (c) 2555 Weerachai. All rights reserved.
07.
//
08.
09.
#import <UIKit/UIKit.h>
10.
11.
@interface
ViewController :
UIViewController
<
UITableViewDataSource
,
UITableViewDelegate
>
12.
{
13.
14.
IBOutlet
UITableView
*myTable;
15.
16.
}
17.
18.
@property
(
nonatomic
,assign)
NSMutableData
*receivedData;
19.
20.
@end
ViewController.m
001.
//
002.
// ViewController.m
003.
// NSURLConnectioJSON
004.
//
005.
// Created by Weerachai on 12/8/55 BE.
006.
// Copyright (c) 2555 Weerachai. All rights reserved.
007.
//
008.
009.
#import "ViewController.h"
010.
011.
@interface
ViewController ()
012.
{
013.
NSMutableArray
*myObject;
014.
015.
// A dictionary object
016.
NSDictionary
*dict;
017.
018.
// Define keys
019.
NSString
*galleryid;
020.
NSString
*name;
021.
NSString
*titlename;
022.
NSString
*thumbnail;
023.
}
024.
025.
@end
026.
027.
@implementation
ViewController
028.
029.
@synthesize
receivedData;
030.
031.
- (
void
)viewDidLoad
032.
{
033.
[
super
viewDidLoad];
034.
035.
// Do any additional setup after loading the view, typically from a nib.
036.
037.
// Define keys
038.
galleryid = @
"GalleryID"
;
039.
name = @
"Name"
;
040.
titlename = @
"TitleName"
;
041.
thumbnail = @
"Thumbnail"
;
042.
043.
// Create array to hold dictionaries
044.
myObject = [[
NSMutableArray
alloc] init];
045.
046.
047.
NSURLRequest
*theRequest =
048.
[
NSURLRequest
requestWithURL:[
NSURL
URLWithString:@
"http://www.thaicreate.com/url/getGallery.php"
]
049.
cachePolicy:
NSURLRequestReloadIgnoringLocalCacheData
050.
timeoutInterval:10.0];
051.
052.
NSURLConnection
*theConnection=[[
NSURLConnection
alloc] initWithRequest:theRequest delegate:
self
];
053.
054.
055.
if
(theConnection) {
056.
self
.receivedData = [[
NSMutableData
data]
retain
];
057.
}
else
{
058.
UIAlertView
*connectFailMessage = [[
UIAlertView
alloc] initWithTitle:@
"NSURLConnection "
message:@
"Failed in viewDidLoad"
delegate:
self
cancelButtonTitle:@
"Ok"
otherButtonTitles:
nil
];
059.
[connectFailMessage show];
060.
[connectFailMessage release];
061.
}
062.
063.
}
064.
065.
- (
void
)connection:(
NSURLConnection
*)connection didReceiveResponse:(
NSURLResponse
*)response
066.
{
067.
[receivedData setLength:0];
068.
}
069.
070.
- (
void
)connection:(
NSURLConnection
*)connection didReceiveData:(
NSData
*)data
071.
{
072.
[receivedData appendData:data];
073.
}
074.
075.
- (
void
)connection:(
NSURLConnection
*)connection didFailWithError:(
NSError
*)error
076.
{
077.
078.
[connection release];
079.
[receivedData release];
080.
081.
// inform the user
082.
UIAlertView
*didFailWithErrorMessage = [[
UIAlertView
alloc] initWithTitle: @
"NSURLConnection "
message: @
"didFailWithError"
delegate:
self
cancelButtonTitle: @
"Ok"
otherButtonTitles:
nil
];
083.
[didFailWithErrorMessage show];
084.
[didFailWithErrorMessage release];
085.
086.
//inform the user
087.
NSLog
(@
"Connection failed! Error - %@"
, [error localizedDescription]);
088.
089.
}
090.
091.
- (
void
)connectionDidFinishLoading:(
NSURLConnection
*)connection
092.
{
093.
if
(receivedData)
094.
{
095.
//NSLog(@"%@",receivedData);
096.
//NSString *dataString = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
097.
//NSLog(@"%@",dataString);
098.
099.
id
jsonObjects = [
NSJSONSerialization
JSONObjectWithData:receivedData options:
NSJSONReadingMutableContainers
error:
nil
];
100.
101.
// values in foreach loop
102.
for
(
NSDictionary
*dataDict in jsonObjects) {
103.
NSString
*strGalleryID = [dataDict objectForKey:@
"GalleryID"
];
104.
NSString
*strName = [dataDict objectForKey:@
"Name"
];
105.
NSString
*strTitleName = [dataDict objectForKey:@
"TitleName"
];
106.
NSString
*strThumbnail = [dataDict objectForKey:@
"Thumbnail"
];
107.
108.
dict = [
NSDictionary
dictionaryWithObjectsAndKeys:
109.
strGalleryID, galleryid,
110.
strName, name,
111.
strTitleName, titlename,
112.
strThumbnail, thumbnail,
113.
nil
];
114.
[myObject addObject:dict];
115.
}
116.
117.
[myTable reloadData];
118.
}
119.
120.
121.
// release the connection, and the data object
122.
[connection release];
123.
[receivedData release];
124.
}
125.
126.
- (
NSInteger
)tableView:(
UITableView
*)tableView numberOfRowsInSection:(
NSInteger
)section
127.
{
128.
129.
int
nbCount = [myObject count];
130.
if
(nbCount == 0)
131.
return
1;
132.
else
133.
return
[myObject count];
134.
135.
}
136.
137.
- (
UITableViewCell
*)tableView:(
UITableView
*)tableView cellForRowAtIndexPath:(
NSIndexPath
*)indexPath
138.
{
139.
140.
int
nbCount = [myObject count];
141.
142.
static
NSString
*CellIdentifier = @
"Cell"
;
143.
144.
UITableViewCell
*cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
145.
if
(cell ==
nil
) {
146.
// Use the default cell style.
147.
cell = [[[
UITableViewCell
alloc] initWithStyle :
UITableViewCellStyleSubtitle
148.
reuseIdentifier : CellIdentifier] autorelease];
149.
}
150.
151.
if
(nbCount ==0)
152.
cell.textLabel.text = @
"Loading Data"
;
153.
else
154.
{
155.
NSDictionary
*tmpDict = [myObject objectAtIndex:indexPath.row];
156.
157.
NSURL
*url = [
NSURL
URLWithString:[tmpDict objectForKey:thumbnail]];
158.
NSData
*data = [
NSData
dataWithContentsOfURL:url];
159.
UIImage
*img = [[
UIImage
alloc] initWithData:data];
160.
cell.imageView.image = img;
161.
162.
cell.textLabel.text = [tmpDict objectForKey:name];
163.
cell.detailTextLabel.text= [tmpDict objectForKey:titlename];
164.
}
165.
166.
//[tmpDict objectForKey:galleryid]
167.
//[tmpDict objectForKey:name]
168.
//[tmpDict objectForKey:titlename]
169.
//[tmpDict objectForKey:thumbnail]
170.
171.
return
cell;
172.
}
173.
174.
175.
176.
- (
void
)didReceiveMemoryWarning
177.
{
178.
[
super
didReceiveMemoryWarning];
179.
// Dispose of any resources that can be recreated.
180.
}
181.
182.
- (
void
)dealloc {
183.
[myTable release];
184.
[
super
dealloc];
185.
}
186.
@end
Screenshot

แสดงข้อมูลบน Table View ซึ่งอ่านมาจาก URL ทำงานด้วย PHP กับ MySQL ผ่าน Class ของ NSURLConnection
CD:http://www.thaicreate.com/mobile/ios-iphone-nsurlconnection-php-mysql-json.html
Comments
Post a Comment