1
我是Swift语言和iOS平台的新开发人员。我一直在阅读许多关于在表中实现搜索功能的指南和教程。在tableview中搜索与数据库数据分裂成许多数组?
但是,没有一个符合我的需求。所以,我的问题是:我将如何去执行一个从数据库中获取数据并从4个数组填充的表的搜索?
表的代码
import UIKit
class VieworderTVC: UIViewController,UITableViewDataSource, UITableViewDelegate {
var deleteOrderIndexPath: NSIndexPath? = nil
@IBAction func btnRefresh(sender: UIBarButtonItem) {
orderIDData.removeAll()
ItemNoData.removeAll()
BPnoData.removeAll()
QuantityData.removeAll()
self.tblview.reloadData()
get_data_from_url("http://100.1.1.25/sfc/orders.php")
return
}
@IBOutlet weak var tblview: UITableView!;
var orderIDData:Array<String> = Array <String>()
var ItemNoData:Array<String> = Array <String>()
var BPnoData:Array<String> = Array <String>()
var QuantityData:Array<String> = Array <String>()
override func viewDidLoad() {
super.viewDidLoad()
get_data_from_url("http://100.1.1.25/sfc/orders.php")
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return orderIDData.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! OrderViewCell
print(indexPath.row)
cell.orderLabel.text = orderIDData[indexPath.row]
cell.lblitem.text = ItemNoData[indexPath.row]
cell.lblbp.text = BPnoData[indexPath.row]
cell.lblquantity.text = QuantityData[indexPath.row]
return cell
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
deleteOrderIndexPath = indexPath
let OrderToDelete = orderIDData[indexPath.row]
confirmDelete(OrderToDelete)
}
}
// Delete Confirmation and Handling
func confirmDelete(planet: String) {
let alert = UIAlertController(title: "Delete Planet", message: "Are you sure you want to permanently delete order \(planet)?", preferredStyle: .ActionSheet)
let DeleteAction = UIAlertAction(title: "Delete", style: .Destructive, handler: handleDeletePlanet)
let CancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: cancelDeleteOrder)
alert.addAction(DeleteAction)
alert.addAction(CancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
func handleDeletePlanet(alertAction: UIAlertAction!) -> Void {
if let indexPath = deleteOrderIndexPath {
tblview.beginUpdates()
let OrderNo = orderIDData[indexPath.row];
let myUrl = NSURL(string: "http://100.1.1.25/sfc/deleteorder.php");let request = NSMutableURLRequest(URL:myUrl!);
request.HTTPMethod = "POST";
// Compose a query string
let postString = "OrderNo=\(OrderNo)";
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
print("error=\(error)")
return
}
// You can print out response object
print("response = \(response)")
// Print out response body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
//Let’s convert response sent from a server side script to a NSDictionary object:
//var err: NSError?
let myJSON = try! NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
if let parseJSON = myJSON {
let resultValue = parseJSON["status"] as? String!;
print("result: \(resultValue)");
var isOrderDeleted:Bool = false;
if (resultValue == "Success") {isOrderDeleted = true;}
var DisplayMessage: String = parseJSON["message"] as! String!;
if (!isOrderDeleted) {
DisplayMessage = parseJSON["message"] as! String!
}
dispatch_async(dispatch_get_main_queue(), {
let alerting = UIAlertController(title:"Alert", message:DisplayMessage, preferredStyle: UIAlertControllerStyle.Alert);
let ok = UIAlertAction(title: "Ok", style:UIAlertActionStyle.Default, handler: nil)
alerting.addAction(ok);
self.presentViewController(alerting, animated: true, completion: nil)
});
}
}
task.resume()
orderIDData.removeAtIndex(indexPath.row)
ItemNoData.removeAtIndex(indexPath.row)
BPnoData.removeAtIndex(indexPath.row)
QuantityData.removeAtIndex(indexPath.row)
// Note that indexPath is wrapped in an array: [indexPath]
tblview.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic)
deleteOrderIndexPath = nil
tblview.endUpdates()
}
}
func cancelDeleteOrder(alertAction: UIAlertAction!) {
deleteOrderIndexPath = nil
}
func get_data_from_url(url:String)
{
let httpMethod = "GET"
let url = NSURL(string: url)
let urlRequest = NSMutableURLRequest(URL: url!,
cachePolicy: .ReloadIgnoringLocalAndRemoteCacheData,
timeoutInterval: 15.0)
let queue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(
urlRequest,
queue: queue,
completionHandler: {(response: NSURLResponse?,
data: NSData?,
error: NSError?) in
if data!.length > 0 && error == nil{
let json = NSString(data: data!, encoding: NSASCIIStringEncoding)
self.extract_json(json!)
}else if data!.length == 0 && error == nil{
print("Nothing was downloaded")
} else if error != nil{
print("Error happened = \(error)")
}
}
)
}
func extract_json(data:NSString)
{
//let parseError: NSError?
let jsonData:NSData = data.dataUsingEncoding(NSASCIIStringEncoding)!
let json: AnyObject? = try! NSJSONSerialization.JSONObjectWithData(jsonData, options: .MutableContainers)
if let orders_list = json as? NSArray
{
for (var i = 0; i < orders_list.count ; i++)
{
if let orders_obj = orders_list[i] as? NSDictionary
{
if let order_id = orders_obj["OrderID"] as? String
{
if let order_ItemNo = orders_obj["ItemNo"] as? String
{
if let order_bpNo = orders_obj["BPno"] as? String
{
if let order_quantity = orders_obj["Quantity"] as? String
{
//TableData.append(order_id + " [" + order_ItemNo + "]")
orderIDData.append(order_id)
ItemNoData.append(order_ItemNo)
BPnoData.append(order_bpNo)
QuantityData.append(order_quantity)
}
}
}
}
}
}
}
do_table_refresh();
}
func do_table_refresh()
{
dispatch_async(dispatch_get_main_queue(), {
self.tblview.reloadData()
return
})
}
import UIKit
class OrderViewCell: UITableViewCell {
@IBOutlet weak var orderLabel: UILabel!
@IBOutlet weak var lblitem: UILabel!
@IBOutlet weak var lblquantity: UILabel!
@IBOutlet weak var lblbp: UILabel!
}