当我通过 GitHub API 的
UITextField
获取数据时,我找不到将数据传递给 Child VC 的方法
protocol GithubManagerDelegate {
func didUpdateGithub(_ githubManager: GithubManager, github: GithubModel)
func didFailWithError(error: Error)
}
struct GithubManager {
let profileUrl = "https://api.github.com/users"
let clientId = // deleted this
let secretId = // deleted this
var delegate: GithubManagerDelegate?
func fetchProfile(profileName: String) {
let urlString = "\(profileUrl)/\(profileName)?client_id=\(clientId)&client_secret=\(secretId)"
performRequest(with: urlString)
}
func performRequest(with urlString: String) {
if let url = URL(string: urlString) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
self.delegate?.didFailWithError(error: error!)
return
}
if let safeData = data {
if let github = self.parseJSON(safeData) {
self.delegate?.didUpdateGithub(self, github: github)
print(github)
}
}
}
task.resume()
}
}
func parseJSON(_ githubData: Data) -> GithubModel? {
let decoder = JSONDecoder()
do {
let decodeData = try decoder.decode(GithubData.self, from: githubData)
let name = decodeData.name ?? "The user does not have a name"
let login = decodeData.login ?? "No username by this name." // TODO: Change to give a alert
let avatarUrl = decodeData.avatar_url
let blog = decodeData.blog ?? "No Blog"
let bio = decodeData.bio ?? "No Bio"
let location = decodeData.location ?? "No location"
let followers = decodeData.followers
let following = decodeData.following
let github = GithubModel(githubName: login, githubUser: name, githubAvatar: avatarUrl, githubBio: bio, githubLocation: location, githubBlog: blog, githubFollowers: followers, githubFollowing: following)
return github
} catch {
delegate?.didFailWithError(error: error)
return nil
}
}
}
在父 VC 的 textFieldDidEndEditing 中,我获取输入文本并使用它从 GithubAPI 获取信息
if let username = searchTextField.text {
DispatchQueue.main.async {
self.githubManager.fetchProfile(profileName: username)
}
}
然后在我的 Child VC 中,我使用
GithubManagerDelegate
(其中我使用 DispatchQueue
)来用信息填充标签。但信息是空的,因为一旦收到数据我就无法将其传递给孩子。
func didUpdateGithub(_ githubManager: GithubManager, github: GithubModel) {
DispatchQueue.main.async {
self.usernameLabel.text = github.githubName
}
}
我从 ParentVC 到 ChildVC 的方式:
navigationController?.pushViewController(profileVC,动画:true)
希望我清楚问题所在......
当您尝试在
parent
ViewController 和 child
ViewController 之间传递数据时,您应该向子级添加子级而不是导航。
在
child
ViewController 中:var passingName: String?
例如
let child = #YourChildViewController insitiate it.
self.addChild(child)
child.passingName = passingName
self.view.addSubview(child.view)
child.didMove(toParent: self)
希望这个解决方案对您有帮助