简体   繁体   English

如何在 Alamofire 中使用 UITextField?

[英]How To Use a UITextField with Alamofire?

I recently started using Alamofire over URLSession just to be comfortable in it and switching to a more readable a easy code base.我最近开始在 URLSession 上使用 Alamofire 只是为了适应它并切换到更易读的简单代码库。 I am creating an app where I have a UITextField and whenever the user writes something and hits return, it searches through the API for the specific data.我正在创建一个应用程序,其中我有一个 UITextField 并且每当用户写一些东西并点击返回时,它都会在 API 中搜索特定数据。 I would like to start out by printing that data into the console for the moment, but I can't figure out how to do that.我现在想先将该数据打印到控制台中,但我不知道该怎么做。 How can I achieve that to search any specific data from my Model?如何从我的 Model 中搜索任何特定数据?

EDIT: The base URL looks like this: " https://api.themoviedb.org/3/search/movie?api_key=[API_KEY] ".编辑:基础 URL 看起来像这样:“ https://api.themoviedb.org/3/search/movie?api_key=[API_KEY] ”。 To search for a specific title we add "&query=[name of the movie]".要搜索特定标题,我们添加“&query=[电影名称]”。 How can I add that last part for the query to what the user inputs in the textfield?如何将查询的最后一部分添加到用户在文本字段中输入的内容中?

PS:I used ObjectMapper for my Model. PS:我为我的 Model 使用了 ObjectMapper。

If we get default API call response as json like this如果我们像这样得到默认的 API 调用响应为 json

"success" : true,
"message" : "successfull"
"data" : {
       "field1" : "some data"
       }
}

So we can handle this response like this所以我们可以像这样处理这个响应

AF.request(URL(string: "myurl.com")!,
               method: .get, 
               headers: AppConstants.headers)
        .validate(statusCode:200..<300)
        .validate(contentType:[AppConstants.contentTypeJson])
        .responseJSON { (response) in
            switch response.result {
            case .success(let data):
                guard let json = data as? [String:AnyObject] else {
                    return
                }

                let isSuccess =  (json["success"])?.boolValue ?? false
                if isSuccess {
                    print(json) //You can do something with response
                }else{
                    Data.currentError = (json["message"]) as? String ?? "-"
                }

            case .failure(let error):
                print(error)
            }
    }

more info: https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling更多信息: https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#response-handling

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM