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


iOS/iPhone Search Data from Web Server (URL,Website)

iOS/iPhone Search Data from Web Server (URL,Website) บทความนี้จะเรียนรู้วิธีการ Search หรือค้นหาข้อมูลที่อยู่บน Web Server โดยใช้ NSURLConnection ส่ง Keyword ที่ต้องการค้นหา ผ่าน POST ไปยัง URL ของ Web Server ที่ทำหน้าที่โดย PHP กับ MySQL และหลังจากที่ PHP รับค่า POST แล้วทำการค้นหาข้อมูลออกมาได้แล้ว ก็จะส่งค่ากลับมายัง Client ในรูปแบบของ JSON Data

iOS/iPhone Search Data from Web Server (URL,Website)

iOS/iPhone Search Data from Web Server (URL,Website)


วิธีการแบบนี้จะดีกว่าการโหลดข้อมูลมาทั้งหมดแล้วค่อยใช้ Search Bar เพราะเมื่อข้อมูลมีปริมาณมาก หลายพันหรือหมื่น Record การที่จะโหลดข้อมูลมาทั้งหมดแล้วใช้ Search Bar ในการ Filter นั้จะทำให้มีการใช้ Memory ในการจัดเก็บตัวแปรในรุปแบบของ Object เช่น Array นั้นสูงมาก แต่วิธีนี้จะใช้การส่งเฉพาะ Result ที่ค้นหาได้จริง ๆ เท่านั้น

iOS/iPhone Search Bar (UISearchBar) and Table View (UITableView)

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


Example การทำระบบ Search ค้นหาข้อมูลจาก Web Server (URL)

MySQL Database
01.CREATE TABLE `member` (
02.  `MemberID` int(11) NOT NULL auto_increment,
03.  `Name` varchar(50) NOT NULL,
04.  `Tel` varchar(50) NOT NULL,
05.  PRIMARY KEY  (`MemberID`)
06.) ENGINE=MyISAM  AUTO_INCREMENT=4 ;
07. 
08.--
09.-- Dumping data for table `member`
10.--
11. 
12.INSERT INTO `member` VALUES (1, 'Weerachai', '0819876107');
13.INSERT INTO `member` VALUES (2, 'Win', '021978032');
14.INSERT INTO `member` VALUES (3, 'Eak', '0876543210');

โครงสร้างของ MySQL Database

iOS/iPhone Search Data from Web Server (URL,Website)

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

ไฟล์ php ที่รับค่า POST แล้วค้นหาใน MySQL Database



iOS/iPhone Search Data from Web Server (URL,Website)

ทดสอบเรียก php ผ่าน URL โดยไม่ได้ทำการ POST ก็จะแสดงข้อมูลทั้งหมด

iOS/iPhone Search Data from Web Server (URL,Website)

สร้าง Project บน Xcode เลือกแบบ Single View Application

iOS/iPhone Search Data from Web Server (URL,Website)

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

iOS/iPhone Search Data from Web Server (URL,Website)

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

iOS/iPhone Search Data from Web Server (URL,Website)

ลาก Navigation Bar มาวางไว้ในหน้าจอ View

iOS/iPhone Search Data from Web Server (URL,Website)

ใส่ Label บน Navigation Bar

iOS/iPhone Search Data from Web Server (URL,Website)

ลาก Text Fields มาวางไว้บน Navigation Bar

iOS/iPhone Search Data from Web Server (URL,Website)

ตามด้วย Bar Button Item

iOS/iPhone Search Data from Web Server (URL,Website)

เปลี่ยนให้เป็น Icons ของการ Search

iOS/iPhone Search Data from Web Server (URL,Website)

ลาก Table View มาวางไว้ในหน้าจอ View

iOS/iPhone Search Data from Web Server (URL,Website)

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

iOS/iPhone Search Data from Web Server (URL,Website)

ใน Class ของ .h ให้เชื่อม IBOutlet และ IBAction ดังรูป จากนั้นเขียน Code ทั้งหมดดังนี้

ViewController.h
01.//
02.//  ViewController.h
03.//  searchDataFromServer
04.//
05.//  Created by Weerachai on 12/10/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.    IBOutlet UITextField *txtKeyword;
14.     
15.    IBOutlet UITableView *myTable;
16.}
17. 
18.- (IBAction)btnSearch:(id)sender;
19. 
20.@property(nonatomic,assign) NSMutableData *receivedData;
21. 
22.@end




ViewController.m
001.//
002.//  ViewController.m
003.//  searchDataFromServer
004.//
005.//  Created by Weerachai on 12/10/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 *memberid;
020.    NSString *name;
021.    NSString *tel;
022.     
023.    UIAlertView *loading;
024.}
025. 
026. 
027.@end
028. 
029.@implementation ViewController
030. 
031.@synthesize receivedData;
032. 
033.- (void)viewDidLoad
034.{
035.    [super viewDidLoad];
036.    // Do any additional setup after loading the view, typically from a nib.
037.     
038.    // Define keys
039.    memberid = @"MemberID";
040.    name = @"Name";
041.    tel = @"Tel";
042.     
043.    // Create array to hold dictionaries
044.    myObject = [[NSMutableArray alloc] init];
045.     
046.}
047. 
048.- (IBAction)btnSearch:(id)sender {
049.     
050.    //Keyword=abc
051.    NSMutableString *post = [NSString stringWithFormat:@"keyword=%@",[txtKeyword text]];
052.    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
053.    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
054.     
055.    NSURL *url = [NSURL URLWithString:@"https://www.thaicreate.com/url/searchData.php"];
056.    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
057.                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
058.                           timeoutInterval:10.0];
059.    [request setHTTPMethod:@"POST"];
060.    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
061.    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
062.    [request setHTTPBody:postData];
063.     
064.    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
065.     
066.    // Show Progress Loading...
067.    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
068.     
069.    loading = [[UIAlertView alloc] initWithTitle:@"" message:@"Please Wait..." delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
070.    UIActivityIndicatorView *progress= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
071.    progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
072.    [loading addSubview:progress];
073.    [progress startAnimating];
074.    [progress release];
075.    [loading show];
076.     
077.    if (theConnection) {
078.        self.receivedData = nil;
079.    } else {
080.        UIAlertView *connectFailMessage = [[UIAlertView alloc] initWithTitle:@"NSURLConnection " message:@"Failed in viewDidLoad"  delegate: self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
081.        [connectFailMessage show];
082.        [connectFailMessage release];
083.    }
084.     
085.    [myTable reloadData];
086.}
087. 
088.- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
089.{
090.    receivedData = [[NSMutableData alloc] init];
091.}
092. 
093.- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
094.{
095.    sleep(2);
096.    [receivedData appendData:data];
097.}
098. 
099.- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
100.{
101.     
102.    [connection release];
103.    [receivedData release];
104.     
105.    // inform the user
106.    UIAlertView *didFailWithErrorMessage = [[UIAlertView alloc] initWithTitle: @"NSURLConnection " message: @"didFailWithError"  delegate: self cancelButtonTitle: @"Ok" otherButtonTitles: nil];
107.    [didFailWithErrorMessage show];
108.    [didFailWithErrorMessage release];
109.     
110.    //inform the user
111.    NSLog(@"Connection failed! Error - %@", [error localizedDescription]);
112.     
113.}
114. 
115.- (void)connectionDidFinishLoading:(NSURLConnection *)connection
116.{
117.    // Hide Progress
118.    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
119.    [loading dismissWithClickedButtonIndex:0 animated:YES];
120.     
121.    // Clear Object
122.    [myObject removeAllObjects];
123.     
124.    if(receivedData)
125.    {
126.        //NSLog(@"%@",receivedData);
127.        //NSString *dataString = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
128.        //NSLog(@" abc = %@",dataString);
129.         
130.        id jsonObjects = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];
131.         
132.        // values in foreach loop
133.        for (NSDictionary *dataDict in jsonObjects) {
134.            NSString *strMemberID = [dataDict objectForKey:@"MemberID"];
135.            NSString *strName = [dataDict objectForKey:@"Name"];
136.            NSString *strTel = [dataDict objectForKey:@"Tel"];
137.             
138.            dict = [NSDictionary dictionaryWithObjectsAndKeys:
139.                    strMemberID, memberid,
140.                    strName, name,
141.                    strTel, tel,
142.                    nil];
143.            [myObject addObject:dict];
144.        }
145.         
146.        [myTable reloadData];
147.    }
148.     
149.    // release the connection, and the data object
150.    [connection release];
151.    [receivedData release];
152.}
153. 
154.- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
155.{
156.     
157.    int nbCount = [myObject count];
158.    if (nbCount == 0)
159.        return 1;
160.    else
161.        return [myObject count];
162.     
163.}
164. 
165.- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
166.{
167.     
168.    static NSString *CellIdentifier = @"Cell";
169.     
170.    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
171.    if (cell == nil) {
172.        // Use the default cell style.
173.        cell = [[[UITableViewCell alloc] initWithStyle : UITableViewCellStyleSubtitle
174.                                       reuseIdentifier : CellIdentifier] autorelease];
175.    }
176.     
177.    int nbCount = [myObject count];
178.    if (nbCount ==0)
179.        cell.textLabel.text = @"";
180.    else
181.    {
182.        NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
183.         
184.        // MemberID
185.        NSMutableString *text;
186.        text = [NSString stringWithFormat:@"MemberID : %@",[tmpDict objectForKey:memberid]];
187.         
188.        // Name & Tel
189.        NSMutableString *detail;
190.        detail = [NSString stringWithFormat:@"Name : %@ , Tel : %@"
191.                  ,[tmpDict objectForKey:name]
192.                  ,[tmpDict objectForKey:tel]];
193.         
194.        cell.textLabel.text = text;
195.        cell.detailTextLabel.text= detail;
196.         
197.        //[tmpDict objectForKey:memberid]
198.        //[tmpDict objectForKey:name]
199.        //[tmpDict objectForKey:tel]
200.    }
201.    return cell;
202.}
203. 
204.- (void)didReceiveMemoryWarning
205.{
206.    [super didReceiveMemoryWarning];
207.    // Dispose of any resources that can be recreated.
208.}
209. 
210.- (void)dealloc {
211.    [txtKeyword release];
212.    [myTable release];
213.    [super dealloc];
214.}
215. 
216.@end


Screenshot

iOS/iPhone Search Data from Web Server (URL,Website)

ช่องกรอกข้อมูล และ Button สำหรับค้นหา



iOS/iPhone Search Data from Web Server (URL,Website)

กรอก Keyword และทำการค้นหา ซึ่งจะแสดง Progress แบบ Icons หมุ่น ๆ

iOS/iPhone Search Data from Web Server (URL,Website)

แสดงข้อมูลที่ค้นหาจาก Web Server

   
Hate it
Don't like it
It's ok
Like it
Love it
Share


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


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


   


Bookmark.   
       
  By : ThaiCreate.Com Team (บทความเป็นลิขสิทธิ์ของเว็บไทยครีเอทห้ามนำเผยแพร่ ณ เว็บไซต์อื่น ๆ)
  Score Rating :  
  Create/Update Date : 2012-12-13 12:27:02 / 2017-03-26 08:54:31
  Download : Download  iOS/iPhone Search Data from Web Server (URL,Website)
 Sponsored Links / Related

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

 
iOS/iPhone Page Control (UIPageControl) and ScrollView (UIScrollView) (iPhone, iPad)
Rating :

 
iOS/iPhone Hide Input Keyboard and Validate Text Field (Password, Number, URL, E-Mail, Phone Number)
Rating :

 
iOS/iPhone AD BannerView (iAd Framework)
Rating :

 
iOS/iPhone Table View Show Enable Edit / Delete Cell (Swipe To Delete) (UITableView)
Rating :

 
iOS/iPhone Edit Update Data on Web Server (URL,Website)
Rating :

 
iOS/iPhone Delete Remove Data on Web Server (URL,Website)
Rating :

 
iOS/iPhone Register Form and Send Data to Web Server (PHP & MySQL)
Rating :

 
iOS/iPhone Login Username and Password from Web Server (PHP & MySQL)
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
   





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