我在viewController中有一个 usernameTextField ,在其中输入用户名和带有以下代码的按钮 searchTapped :
@IBAction func searchTapped(_ sender: UIButton) {
guard let username = usernameTextField.text, username != "" else {
displayWarningLabel(withText: "Information is incorrect")
return
}
guard let gitUrl = URL(string: "https://api.github.com/users/\(username)/gists") else { return }
URLSession.shared.dataTask(with: gitUrl) { (data, response, error) in
guard let data = data else { return }
guard error == nil else { return }
do {
let gitData = try JSONDecoder().decode([Gists].self, from: data)
DispatchQueue.main.async {
self.gists = gitData
}
} catch let error {
print(error)
}
}.resume()
performSegue(withIdentifier: "GistsSegue", sender: nil)
}
从json获取数据后,我想将数据保存到此方法之外的数组要点中,但这不会发生。
var gists = [Gists]()
可能是什么问题?
以防万一,这是我解析json的模型:
struct Gists: Codable {
var description: String?
var files: [String: DetailGist]
}
struct DetailGist: Codable {
var filename: String?
var raw_url: String?
}
答案 0 :(得分:0)
public class AtdListAdapter extends RecyclerView.Adapter<AtdListAdapter.ViewHolder> {
private List<String> atd ;
private Context context;
String str;
private DatabaseReference demo;
public AtdListAdapter(List<String> atd, Context context) {
this.atd = atd;
this.context = context;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.atdliststaff,null);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(ViewHolder holder, int position) {
str = atd.get(position);
holder.name.setText(str);
}
@Override
public int getItemCount() {
return atd.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
private DatabaseReference demo;
private TextView name;
private RadioButton rb1,rb2;
private RadioGroup rg;
public ViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.name);
rg = itemView.findViewById(R.id.rg);
rb1 = itemView.findViewById(R.id.rb1);
rb2 = itemView.findViewById(R.id.rb2);
if(rb1.isSelected()) {
demo = FirebaseDatabase.getInstance().getReference().child("IDS").child("AtdList").child("1").child("1").child(str).child("status");
demo.setValue("Present");
Toast.makeText(context, "updated by Present", Toast.LENGTH_SHORT).show();
}
else if(rb2.isSelected())
{
demo = FirebaseDatabase.getInstance().getReference().child("IDS").child("AtdList").child("1").child("1").child(str).child("status");
demo.setValue("Absent");
Toast.makeText(context, "Updated by Absent", Toast.LENGTH_SHORT).show();
}
}
}
}
正在被调用,但是在您调用self.gists = gitData
之后很久才被调用。这就是异步数据访问的本质。
只需将您的performSegue
呼叫移到设置performSegue
之后。
self.gists