我的应用程序有一个搜索栏,可以向MySQL数据库发送查询,然后接收JSON响应并在视图中显示它。当响应成功时(MySQL中存在实际的数组和行),这很有用。但是,当响应为空时,我想显示一个带有简单错误的警告框。
当查询响应为空时,我的服务器上的PHP代码设置为echo No rows
,如何在我的应用程序中实现此目的?
这就是我现在要做的事情:
func searchBarSearchButtonClicked(searchBar: UISearchBar)
{
if(searchBar.text!.isEmpty)
{
return
}
doSearch(searchBar.text!)
}
func doSearch(searchWord: String)
{
mySearchBar.resignFirstResponder()
//created NSURL
if let requestURL = NSURL(string: URL_GET_coffees) {
//creating NSMutableURLRequest
let request = NSMutableURLRequest(URL: requestURL)
//setting the method to post
request.HTTPMethod = "POST"
//getting values from search bar text field
let searchText=mySearchBar.text
//creating the post parameter from search bar text field
let postParameters = "searchQuery="+searchText!;
//adding the parameters to request body
request.HTTPBody = postParameters.dataUsingEncoding(NSUTF8StringEncoding)
//creating a task to send the post request
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
//exiting if there is some error
if error != nil{
print("error is \(error)")
self.displayAlertMessage(error!.localizedDescription)
return;
}
//parsing the response
do {
guard let coffees = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSArray else {
//Doesn't exist, or isn't an NSArray
return
}
var newcoffees=[face]()
for coffee in coffees {
//getting the data at each index
let coffeeName = coffee["name"] as! String
let coffeeDirectLink = coffee["calculation_toemail_"] as! String
let coffeeImage = coffee["calculation_toemail_"] as! String
let newface = face(name:coffeeName,
directLink: coffeeDirectLink,
image:coffeeImage)
newcoffees.append(newface)
//displaying the data
print("name -> ", coffeeName)
print("direct_link -> ", coffeeDirectLink)
print("image -> ", coffeeImage)
print("===================")
print()
}
dispatch_async(dispatch_get_main_queue(),{
self.faces = newcoffees
self.collectionview.reloadData()
})
let errorMessage = newcoffees["No rows"] as? String
if(errorMessage != nil)
{
// display an alert message
self.displayAlertMessage(errorMessage!)
}
} catch {
print(error)
}
}
//executing the task
task.resume()
}
}
func displayAlertMessage(userMessage: String)
{
let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil)
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated: true, completion: nil)
}
但是发生的事情是我得到一个Cannot subscript a value of type '[face]' with an index of type 'String'
,我告诉它错误响应是什么。我能做错什么?