我创建了一个项目,它将检索提取的JSON数据并在UITableview中显示它。我不想通过下载所有内容来增加应用程序的负担。因此,只有当用户选择了一行时,它才会检索员工的详细信息。我正在使用页面视图控制器,以便用户可以通过滑动页面来浏览每个页面。 如何将dispatch_sync中发送的页面值发送到detailviewcontroller页面?
这是来自managePageviewController的代码
func viewDetailViewController(index: Int) -> DetailViewController? {
if let storyboard = storyboard,
page = storyboard.instantiateViewControllerWithIdentifier("DetailViewController") as? DetailViewController {
let currentEmployee = employeeStore.searchEmployee[index]
getJson().testsearchJSON(currentEmployee.id, handler: {(employeeDetails) -> Void in
dispatch_sync(dispatch_get_main_queue(), {
page.employee = employeeDetails
page.employeeIndex = index
return page //fail here
})
})
}
return nil
}
这是我的getJSON()。testSearchJSON基金
func testsearchJSON(id:String, handler: (Employee) -> Void) {
let requestURL: NSURL = NSURL(string: (favUrl + id))!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
//retrieve data successfully
if (statusCode == 200) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
if data!.length > 0 && error == nil {
guard let name = json["firstName"] as? String,
let title = json["title"] as? String,
let id = json["id"]!,
let manager = json["managerName"] as? String,
let oa = json["oa"] as? String,
let email = json["email"] as? String,
let department = json["department"] as? String,
let division = json["division"] as? String,
let company = json["company"] as? String
else {
return;
}
let newEmployee = Employee(id: String(id), name: name, title: title, manager: manager, oa: oa, email: email, department: department, division: division, company: company)
//test
handler(newEmployee)
}
} catch {
print("Error with JSON: \(error)")
}
}
}
task.resume()
}
}
这是我的DetailviewController页面
class DetailViewController: UIViewController, UITextFieldDelegate {
// MARK:- Propertise
@IBOutlet var employeePic: UIImageView! //employee picture
@IBOutlet var employeeName: UILabel! // name
@IBOutlet var employeeTitle: UILabel! //job title
@IBOutlet var dateCreated: UILabel!
@IBOutlet var managerName: UITextField!
@IBOutlet var oaName: UITextField!
@IBOutlet var emailField: UITextField!
@IBOutlet var departmentField: UITextField!
@IBOutlet var divisionField: UITextField!
@IBOutlet var companyField: UITextField!
var employee: Employee! {
//add applicataion name
didSet {
navigationItem.title = employee.name
}
}
//current employee index
var employeeIndex: Int!
let dateFormatter: NSDateFormatter = {
let formatter = NSDateFormatter()
formatter.dateStyle = .MediumStyle
formatter.timeStyle = .NoStyle
return formatter
}()
//MARK:- assign values
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
employeeName.text = employee.name
employeeTitle.text = "( " + employee.title + " )"
emailField.text = employee.email
managerName.text = employee.manager
dateCreated.text = dateFormatter.stringFromDate(employee.dateCreated)
oaName.text = employee.oa
departmentField.text = employee.department
divisionField.text = employee.division
companyField.text = employee.company
//retrieve image
employeePic.thumbnails()
employeePic.image = UIImage(named: "Default Image")
}
答案 0 :(得分:0)
尝试喜欢这个
func viewDetailViewController(index: Int) -> DetailViewController? {
if let storyboard = storyboard,
page = storyboard.instantiateViewControllerWithIdentifier("DetailViewController") as? DetailViewController {
let currentEmployee = employeeStore.searchEmployee[index]
getJson().testsearchJSON(currentEmployee.id, handler: {(employeeDetails) -> Void in
page.employee = employeeDetails
page.employeeIndex = index
return page //fail here
})
}
return nil
}
func testsearchJSON(id:String, handler: (Employee) -> Void) {
let requestURL: NSURL = NSURL(string: (favUrl + id))!
let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL)
let semaphore = dispatch_semaphore_create(0);
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(urlRequest) {
(data, response, error) -> Void in
let httpResponse = response as! NSHTTPURLResponse
let statusCode = httpResponse.statusCode
//retrieve data successfully
if (statusCode == 200) {
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)
if data!.length > 0 && error == nil {
guard let name = json["firstName"] as? String,
let title = json["title"] as? String,
let id = json["id"]!,
let manager = json["managerName"] as? String,
let oa = json["oa"] as? String,
let email = json["email"] as? String,
let department = json["department"] as? String,
let division = json["division"] as? String,
let company = json["company"] as? String
else {
dispatch_semaphore_signal(semaphore);
return;
}
let newEmployee = Employee(id: String(id), name: name, title: title, manager: manager, oa: oa, email: email, department: department, division: division, company: company)
//test
handler(newEmployee)
dispatch_semaphore_signal(semaphore);
}
} catch {
dispatch_semaphore_signal(semaphore);
print("Error with JSON: \(error)")
}
}
}
task.resume()
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
}
}
答案 1 :(得分:0)
我认为在这种情况下,最好在DetailViewController中的viewDidLoad或viewWillAppear函数中编写数据。这样的事情:
在MainViewController中:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
viewDetailViewController(index : indexPath.row, employee: employeeStore.searchEmployee[indexPath.row])
}
func viewDetailViewController(index: Int, employee: Employee) {
let detailController = storyboard.instantiateViewControllerWithIdentifier("DetailViewController") as? DetailViewController
detailController.currentEmployee = employee
// present/push/etc detail controller
present(detailViewController, animated: true, completion: nil)
}
在DetailViewController中:
var employee : Employee?
...
override func viewDidLoad() {
super.viewDidLoad()
if let employee = currentEmployee {
getJson().testsearchJSON(employee.id, handler: {(employeeDetails) -> Void in
dispatch_sync(dispatch_get_main_queue(), {
//reload UI for employeeDetails
})
})
}
}
您也可以使用GCD等待块加载,例如GCD组。