Swift iOS HTTP 请求拉取数据并仅显示所选数据值的数据



我在下面有我的代码,它使用 alamofire http 请求从 api 中提取数据。 https://jsonplaceholder.typicode.com/posts 使用的 API。 我可以获取所有数据,但我想知道的是我想获取所有数据,但我只在集合中显示什么,例如标题等于此"sunt aut facere repellat provident occaecati excepturi optio reprehenderit" 仅显示标题哪个值等于什么我在上面已经说过了。例如,有很多名称值,但我只想显示谁的名字:"Dun"。谢谢。

示例 API

{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto"
  },

var getAllDetail: [[String:Any]] = [[String:Any]]()
@IBOutlet var collectionView: UICollectionView!
@IBAction func signOutButtonIsPressed(_ sender: Any) {
    let appDelegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
    appDelegate.showLoginScreen()
}
@IBOutlet var signoutButton: UIButton!
var items = [Item]()
override func viewDidLoad() {
    super.viewDidLoad()
    self.signoutButton.layer.cornerRadius = 3.0
    demoApi()
}
override func viewWillAppear(_ animated: Bool) {
     super.viewWillAppear(animated)
    self.navigationController?.navigationBar.isHidden = true
    self.navigationItem.hidesBackButton =  true
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
     return getAllDetail.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionCell
    if let getTempDetails: [String : Any] = getAllDetail[indexPath.row] {
        cell.nameLabel.text = getTempDetails["title"] as? String  ?? "" //titleArray[indexPath.row]
    }
    return cell
}

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    // handle tap events
    print("You selected cell #(indexPath.item)!")
    if let getTempDetails: [String : Any] = getAllDetail[indexPath.row] {
        print("You selected ID #( getTempDetails["userId"] as? String  ?? "" )!")
    }
}
func demoApi() {
    Alamofire.request("https://jsonplaceholder.typicode.com/posts", method: .get, parameters: nil, encoding: JSONEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) in
        switch(response.result) {
        case .success(_):
            guard let json = response.result.value as! [[String:Any]]? else{ return}
            print("Response (json)")
            for item in json {
                self.getAllDetail.append(item)
                // if let title = item["title"] as? String {
                //   self.titleArray.append(title)
                // }
            }
            if !self.getAllDetail.isEmpty{
                DispatchQueue.main.async {
                    self.collectionView.reloadData()
                }
            }
            break

        case .failure(_):
            print("Error")
            break
        }
    }
}

参考您的示例响应:

{
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipitnsuscipit recusandae consequuntur expedita et cumnreprehenderit molestiae ut ut quas totamnnostrum rerum est autem sunt rem eveniet architecto"
  }

你可以这样使用:-

var dict = response as! NSDictionary
 let title = dict.value(forKey: "title")
 print(title)

 if title == "your text"{
         print("Matched")
    }else{
        print("Not Matched")
    }

编辑在您的 Web 中实施响应:-

示例响应:

    { 
"id": 51, 
"name": "uuuuuuuu", 
"desc": "ahahah", 
"reward": "1.00", 
"sched": "2015-01-01T08:00:00+08:00", 
"parent": "", 
"child": "", 
"occurrence": { 
"name": "once" 
}, 
"status": "expired", 
"date_created": "2018-04-06T11:46:46.131836+08:00", 
"date_modified": "2018-04-09T13:16:44.088716+08:00" 
}

像这样使用:

    let dictOccurence = dict["occurrence"] as! NSDictionary
    let strname = dictOccurence["name"]
    print(strname!)

    if strname == "your text"{
         print("Matched")
    }else{
        print("Not Matched")
    }

最新更新