如何使用AlamoFire搜索JSON API并解码数组

时间:2018-05-11 18:51:31

标签: swift alamofire swift4

我正在搜索JSON API,我需要解码其中的数组。我正在使用AlamoFire。示例:当我输入字母" F"我只想要" F"要显示的单词。我想只搜索数组" name"。任何有关这方面的帮助将不胜感激!

这是我的代码:

func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
    let url = "http://dummy.com/url"
    Alamofire.request(url).responseData { (dataResponse) in
        if let err = dataResponse.error {
            print("Failed to contact", err)
            return
        }

        guard let data = dataResponse.data else { return }
        let dummyString = String(data: data, encoding: .utf8)
        print(dummyString ?? "")

        do {
             let searchResult = try JSONDecoder().decode(SearchResults.self, from: data)
            print("Result Count:", searchResult.id)

        } catch let decodeError {
            print("Failed to decode:", decodeError)
        }
    }
}

struct SearchResults: Decodable {
    let id: String

}

我的API数组如下所示:

{ resultId:" 1", 名称:"食品", }, { resultId:" 2", 名称:"电影", }

2 个答案:

答案 0 :(得分:1)

您的结果位于array format,因此您需要将model这样放置:

let searchResult = try JSONDecoder().decode([SearchResults].self, from: data)

对于搜索,您可以应用过滤器:

let filteredArray = searchResult.filter( { $0.name.contains("f") } )

答案 1 :(得分:0)

正如你所说,你的回答是:

[
 { resultId: "1", name: "Food" }, 
 { resultId: "2", name: "Movies"}
]

所以,你的结构将是,

struct SearchResults: Decodable {
    let resultId: String
    let name: String
}

你会用它作为:

    do {
        let resultArray = try JSONDecoder().decode([SearchResults].self, from: data)
        print("Result Count:", searchResult.id)

    } catch let decodeError {
        print("Failed to decode:", decodeError)
    }

要进行搜索,您应使用filter,因为:

    let searchString = "F"
    let filteredArray = resultArray.filter( { String($0.name.first!) == searchString } )
  

匹配第一个字符 =字符串($ 0.name.first!)== searchText

     

检查名称是否包含搜索文字 = $ 0.name.contains(searchText)

总计:

    do {
        let searchResult = try JSONDecoder().decode([SearchResults].self, from: data)
        let filteredArray = resultArray.filter( { $0.name.contains(searchText) } )
    } catch let decodeError {
        print("Failed to decode:", decodeError)
    }