我有一个NSMutableArray
,我正在尝试创建一个搜索栏。我一直在寻找几个小时,但我找不到任何真正有用的东西,因为我正在使用NSMutableArray
和Firebase。我对斯威夫特不熟悉。我创建了一个表格视图和一个搜索栏。表格视图显示NSMutableArray
的数据。当用户在搜索栏上搜索然后整个帖子出现时,我怎么能这样做呢?
如果有一个帖子包含2个字符串和一个图像,一个字符串是“A City”而另一个字符串是帖子的标题,让我们说当用户只搜索帖子的标题时或者只有城市,然后整个帖子显示。如果结果可能与同一viewcontroller
上的tableview
相同。
到目前为止,我已在viewDidLoad
:
func setUpSearchBar() {
let searchController = UISearchController(searchResultsController: nil)
navigationItem.searchController = searchController
searchController.dimsBackgroundDuringPresentation = true
definesPresentationContext = true
}
我的阵列是这样的:
var posts = NSMutableArray()
我写的唯一真正的东西是搜索栏已设置但功能不正常,因为我没有找到任何可以帮助我的东西,因为我刚接触这个并不确定如何进行搜索酒吧工作。到目前为止,我必须找到的所有教程都是非常正常的数组,如:
var post = ["pear", "orange", "apple"]
但我无法找到如何让搜索迭代我的帖子NSMutableArray
。
如果有人能帮我解决这个问题,我会很高兴。如果可能的话,我不想直接回答一些解释,所以我可以自己学习并自己创建。
这是下载数据并在TableView
import UIKit
import FirebaseStorage
import FirebaseDatabase
import FirebaseAuth
import FirebaseCore
import Firebase
class MainViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var postsTableView: UITableView!
var posts = NSMutableArray()
override func viewDidLoad() {
super.viewDidLoad()
setUpSearchBar()
loadData()
self.postsTableView.delegate = self
self.postsTableView.dataSource = self
// 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.
}
func loadData() {
Database.database().reference().child("posts").queryOrdered(byChild: "timeorder").observeSingleEvent(of: .value) { (snapshot) in
if let postsDictionary = snapshot.value as? [String: AnyObject] {
for post in postsDictionary {
self.posts.add(post.value)
}
self.postsTableView.reloadData()
}
}
}
// MARK: - Table view data source
func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return self.posts.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! PostTableViewCell
// Configure the cell...
let post = self.posts[indexPath.row] as! [String: AnyObject]
cell.titleLabel.text = post["title"] as? String
cell.contentTextView.text = post["content"] as? String
cell.dateAndTimeLabel.text = post["time"] as? String
cell.usernameLabel.text = post["username"] as? String
cell.locationAdressLabel.text = post["adress"] as? String
if let imageName = post["image"] as? String {
let imageRef = Storage.storage().reference().child("images/\(imageName)")
imageRef.getData(maxSize: 25 * 1024 * 1024) { (data, error) -> Void in
if error == nil {
//successfull
let downloadedImage = UIImage(data: data!)
cell.postsImageView.image = downloadedImage
}else {
// error
print("there was an error downloading image: \(String(describing: error?.localizedDescription))")
}
}
}
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 500.0
}
@IBAction func goToProfilePage(_ sender: Any) {
let logoutSuccess = self.storyboard?.instantiateViewController(withIdentifier: "ProfileVC")
self.present(logoutSuccess!, animated: true, completion: nil)
}
@IBAction func navigateButton(_ sender: Any) {
let navigate = self.storyboard?.instantiateViewController(withIdentifier: "NavigateVC")
self.present(navigate!, animated: true, completion: nil)
}
@IBAction func chooseCountry(_ sender: Any) {
let navigate = self.storyboard?.instantiateViewController(withIdentifier: "CountryVC")
self.present(navigate!, animated: true, completion: nil)
}
func setUpSearchBar() {
let searchController = UISearchController(searchResultsController: nil)
navigationItem.searchController = searchController
searchController.dimsBackgroundDuringPresentation = true
definesPresentationContext = true
}
以下是将post
上传到Firebase
import UIKit
import FirebaseDatabase
import FirebaseStorage
import FirebaseAuth
import Firebase
class PostViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate, UIPickerViewDataSource, UIPickerViewDelegate {
@IBOutlet weak var addImageButton: UIBarButtonItem!
@IBOutlet weak var pickCountryPicker: UIPickerView!
@IBOutlet weak var choosenCountryLabel: UILabel!
@IBOutlet weak var titleTextField: UITextField!
@IBOutlet weak var contentTextView: UITextView!
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var locationAdressTextField: UITextField!
var imageFileName = ""
var timeStamps = ""
var secondTimeStamps = ""
override func viewDidLoad() {
super.viewDidLoad()
let currentDateTime = Date()
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm"
timeStamps = "\(dateFormatter.string(from: currentDateTime))"
let secondDateFormatter = DateFormatter()
secondDateFormatter.dateFormat = "yyyy-MM-dd HH:00:00"
secondTimeStamps = "\(secondDateFormatter.string(from: currentDateTime))"
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func postButton(_ sender: Any) {
if (self.imageFileName != "") {
if choosenCountryLabel.text == "Afghanistan" {
// image has finshed the uploading, Saving Post!!!
if let uid = Auth.auth().currentUser?.uid {
Database.database().reference().child("users").child(uid).observeSingleEvent(of: .value, with: { (snapshot) in
if let userDictionary = snapshot.value as? [String: AnyObject] {
for user in userDictionary{
if let username = user.value as? String {
if let streetAdress = self.locationAdressTextField.text {
if let title = self.titleTextField.text {
if let content = self.contentTextView.text {
let postObject: Dictionary<String, Any> = [
"uid" : uid,
"title" : title,
"content" : content,
"username" : username,
"time" : self.timeStamps,
"timeorder" : self.secondTimeStamps,
"image" : self.imageFileName,
"adress" : streetAdress
]
Database.database().reference().child("posts").childByAutoId().setValue(postObject)
Database.database().reference().child("Afghanistanposts").childByAutoId().setValue(postObject)
Database.database().reference().child(uid).childByAutoId().setValue(postObject)
let alertPosting = UIAlertController(title: "Successfull upload", message: "Your acty was successfully uploaded.", preferredStyle: .alert)
alertPosting.addAction(UIAlertAction(title: "OK", style: .default, handler: { (action) in
let vc = self.storyboard?.instantiateViewController(withIdentifier: "AfghanistanVC")
self.present(vc!, animated: true, completion: nil)
}))
self.present(alertPosting, animated: true, completion: nil)
print("Posted Succesfully to Firebase, Saving Post!!!")
}
}
}
}
}
}
})
}
}
}else{
let alertNotPosting = UIAlertController(title: "Seems like you got connection problems", message: "Your image has not been uploaded. Please Wait 10 seconds and try again.", preferredStyle: .alert)
alertNotPosting.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertNotPosting, animated: true, completion: nil)
}
@IBAction func addImage(_ sender: Any) {
if addImageButton.isEnabled == false {
let alertNotPosting = UIAlertController(title: "Image already Picked", message: "sorry you already have an image picked", preferredStyle: .alert)
alertNotPosting.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertNotPosting, animated: true, completion: nil)
}else {
let picker = UIImagePickerController()
picker.delegate = self
self.present(picker, animated: true, completion: nil)
}
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
self.imageView.image = pickedImage
uploadImage(image: pickedImage)
picker.dismiss(animated: true, completion: nil)
addImageButton.isEnabled = false
}
}
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
func uploadImage(image: UIImage){
let randomName = randomStringWithLength(length: 10)
let imageData = UIImageJPEGRepresentation(image, 1.0)
let uploadRef = Storage.storage().reference().child("images/\(randomName).jpg")
let uploadTask = uploadRef.putData(imageData!, metadata: nil) { metadata, error in
if error == nil {
//success
print("SuccessFully uploaded")
self.imageFileName = "\(randomName as String).jpg"
}else {
// not success = error
print("error with the Image: \(String(describing: error?.localizedDescription))")
}
}
}
func randomStringWithLength(length: Int) -> NSString {
let characters: NSString = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString: NSMutableString = NSMutableString(capacity: length)
for i in 0..<length {
var len = UInt32(characters.length)
var rand = arc4random_uniform(len)
randomString.appendFormat("%C", characters.character(at: Int(rand)))
}
return randomString
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return countries[row]
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return countries.count
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
choosenCountryLabel.text = countries[row]
}
}
以下是一个充满挑选者国家/地区的数组,并且无需显示。
答案 0 :(得分:-1)
为什么不将NSMutableArray
转换为Swift数组?为安全起见,我建议使用guard
语句,如下所示:
guard let swiftArrayPosts = posts as? [String] else { return }
然后你可以使用像filter
这样的Swift高阶函数来查找你想要的帖子:
let filteredPosts = swiftArrayPosts.filter { $0 == "MyQuery" }
然后将filteredPosts
分配给您用于显示它们的任何数据源。