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 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
CREATE TABLE `member` (
  `MemberID` int(11) NOT NULL auto_increment,
  `Name` varchar(50) NOT NULL,
  `Tel` varchar(50) NOT NULL,
  PRIMARY KEY  (`MemberID`)
) ENGINE=MyISAM  AUTO_INCREMENT=4 ;

-- 
-- Dumping data for table `member`
-- 

INSERT INTO `member` VALUES (1, 'Weerachai', '0819876107');
INSERT INTO `member` VALUES (2, 'Win', '021978032');
INSERT INTO `member` VALUES (3, 'Eak', '0876543210');

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

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

searchData.php
<?php
	$strKeyword = $_POST["keyword"];

	$objConnect = mysql_connect("localhost","root","root");
	$objDB = mysql_select_db("mydatabase");
	$strSQL = "SELECT * FROM member WHERE Name LIKE '%".$strKeyword."%' ";
	$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 ที่รับค่า 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
//
//  ViewController.h
//  searchDataFromServer
//
//  Created by Weerachai on 12/10/55 BE.
//  Copyright (c) 2555 Weerachai. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>
{
    IBOutlet UITextField *txtKeyword;
    
    IBOutlet UITableView *myTable;
}

- (IBAction)btnSearch:(id)sender;

@property(nonatomic,assign) NSMutableData *receivedData;

@end









ViewController.m
//
//  ViewController.m
//  searchDataFromServer
//
//  Created by Weerachai on 12/10/55 BE.
//  Copyright (c) 2555 Weerachai. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()
{
    NSMutableArray *myObject;
    
    // A dictionary object
    NSDictionary *dict;
    
    // Define keys
    NSString *memberid;
    NSString *name;
    NSString *tel;
    
    UIAlertView *loading;
}


@end

@implementation ViewController

@synthesize receivedData;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    
    // Define keys
    memberid = @"MemberID";
    name = @"Name";
    tel = @"Tel";
    
    // Create array to hold dictionaries
    myObject = [[NSMutableArray alloc] init];
    
}

- (IBAction)btnSearch:(id)sender {
    
    //Keyword=abc
    NSMutableString *post = [NSString stringWithFormat:@"keyword=%@",[txtKeyword text]];
    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    
    NSURL *url = [NSURL URLWithString:@"https://www.thaicreate.com/url/searchData.php"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
                           cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                           timeoutInterval:10.0];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody:postData];
    
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
    
    // Show Progress Loading...
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    loading = [[UIAlertView alloc] initWithTitle:@"" message:@"Please Wait..." delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    UIActivityIndicatorView *progress= [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(125, 50, 30, 30)];
    progress.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
    [loading addSubview:progress];
    [progress startAnimating];
    [progress release];
    [loading show];
    
    if (theConnection) {
        self.receivedData = nil;
    } else {
		UIAlertView *connectFailMessage = [[UIAlertView alloc] initWithTitle:@"NSURLConnection " message:@"Failed in viewDidLoad"  delegate: self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
		[connectFailMessage show];
		[connectFailMessage release];
    }
    
    [myTable reloadData];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    receivedData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    sleep(2);
    [receivedData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    
    [connection release];
    [receivedData release];
    
    // inform the user
    UIAlertView *didFailWithErrorMessage = [[UIAlertView alloc] initWithTitle: @"NSURLConnection " message: @"didFailWithError"  delegate: self cancelButtonTitle: @"Ok" otherButtonTitles: nil];
    [didFailWithErrorMessage show];
    [didFailWithErrorMessage release];
	
    //inform the user
    NSLog(@"Connection failed! Error - %@", [error localizedDescription]);
    
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Hide Progress
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [loading dismissWithClickedButtonIndex:0 animated:YES];
    
    // Clear Object
    [myObject removeAllObjects];
    
    if(receivedData)
    {
        //NSLog(@"%@",receivedData);
        //NSString *dataString = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
        //NSLog(@" abc = %@",dataString);
        
        id jsonObjects = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableContainers error:nil];
        
        // values in foreach loop
        for (NSDictionary *dataDict in jsonObjects) {
            NSString *strMemberID = [dataDict objectForKey:@"MemberID"];
            NSString *strName = [dataDict objectForKey:@"Name"];
            NSString *strTel = [dataDict objectForKey:@"Tel"];
            
            dict = [NSDictionary dictionaryWithObjectsAndKeys:
                    strMemberID, memberid,
                    strName, name,
                    strTel, tel,
                    nil];
            [myObject addObject:dict];
        }
        
        [myTable reloadData];
    }
    
    // release the connection, and the data object
    [connection release];
    [receivedData release];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    int nbCount = [myObject count];
    if (nbCount == 0)
        return 1;
    else
        return [myObject count];
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        // Use the default cell style.
        cell = [[[UITableViewCell alloc] initWithStyle : UITableViewCellStyleSubtitle
                                       reuseIdentifier : CellIdentifier] autorelease];
    }
    
    int nbCount = [myObject count];
    if (nbCount ==0)
        cell.textLabel.text = @"";
    else
    {
        NSDictionary *tmpDict = [myObject objectAtIndex:indexPath.row];
        
        // MemberID
        NSMutableString *text;
        text = [NSString stringWithFormat:@"MemberID : %@",[tmpDict objectForKey:memberid]];
        
        // Name & Tel
        NSMutableString *detail;
        detail = [NSString stringWithFormat:@"Name : %@ , Tel : %@"
                  ,[tmpDict objectForKey:name]
                  ,[tmpDict objectForKey:tel]];
        
        cell.textLabel.text = text;
        cell.detailTextLabel.text= detail;
        
        //[tmpDict objectForKey:memberid]
        //[tmpDict objectForKey:name]
        //[tmpDict objectForKey:tel]
    }
    return cell;
}

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

- (void)dealloc {
    [txtKeyword release];
    [myTable release];
    [super dealloc];
}

@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

   
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
   







Load balance : Server 03
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 อัตราราคา คลิกที่นี่