从Alamofire请求打印数据,swift
我提出这一要求:从Alamofire请求打印数据,swift,swift,xcode,get,alamofire,Swift,Xcode,Get,Alamofire,我提出这一要求: func AlamofireGetCode() { let username: String = searchTextField.text! var url:String! url = "https:// ... " AF.request(url, method: .get, encoding: JSONEncoding.default) .responseJSON { response in switc
func AlamofireGetCode()
{
let username: String = searchTextField.text!
var url:String!
url = "https:// ... "
AF.request(url, method: .get, encoding: JSONEncoding.default)
.responseJSON { response in
switch response.result {
case .success:
debugPrint(response)
case .failure(let error):
fatalError("\(error)")
}
}
}
我得到了不同领域的回应:
[Result]: success({
"incomplete_results" = 0;
items = (
{
"username" = " ... "
...
如何在Swift中获取特定字段,如“用户名”?
我想拥有所有用户的用户名并存储它们,你能帮我吗 粘贴您的响应以查看对象的结构。它将显示您可以使用下标访问的所有键和值。您需要提供一个类型来解析JSON响应。使用像quicktype.io这样的站点可以从JSON生成一个,但是任何
可解码的
类型都可以。然后,您可以使用Alamofire的responseDecodable
处理程序来解析您的响应
AF.request(url).responseDecodable(of:TypeToParse.self){response in
调试打印(响应)
}
谢谢,您的回复完全符合我的要求。我能再问一个吗?如果用户希望在另一个视图中访问一个特定字段,如“用户名”,该怎么办?我在类外声明了Struct,因此可以在其他视图中访问它,但无法获取用户名数据。我的Struct类似于Struct UserInfo:Codable{let totalCount:Int let incompleteResults:Bool let items:[Item]enum CodingKeys:String,CodingKey{case totalCount=“total\u count”case incompleterresults=“complete_results”case items}//MARK:-Item struct Item:Codable{let login:String let id:Int let avatarURL:String enum CodingKey:String,CodingKey{case login,id case avatarURL=“avatar_url”}很可能需要使用完成处理程序将接收到的和解析后的响应传递回其他需要它的屏幕。我建议你调查一下。