执行一些指令后无法从一个视图转到另一个视图
Can't go from a view to another after doing some instructions
我在我的应用程序的一部分中有此实现:
为什么当我点击 "cerca per ISBN" 按钮时它会转到 tableView 而没有执行我编写的说明?
这是我点击的 "cerca per ISBN" 按钮的代码:
@IBAction func ISBNButtonClick(_ sender: Any) {
let libro = Libro.text! as String
if Libro.text!.isEmpty {
//Alert per segnalare i campi mancanti, oltre a caselle rosse
var myAlert = UIAlertController(title:"Attenzione\n", message:"Inserire il codice ISBN", preferredStyle:UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default){ action in }
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
// placeholder rosso se la text è vuota
Libro.attributedPlaceholder = NSAttributedString(string:"Digita qui...", attributes: [NSForegroundColorAttributeName: UIColor.red])
//se tutti i campi obbligatori sono stati inseriti, proseguo ad altri controlli
}else{
if(isNumeric(string: libro)){
if((libro.characters.count) < 13 || (libro.characters.count) > 13){
//Alert per segnalare l'ISBN più corto di 13 numeri
var myAlert = UIAlertController(title:"Attenzione\n", message:"L'ISBN deve essere di 13 cifre", preferredStyle:UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default){ action in }
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}else{
//inviare dati al server
let myUrl = NSURL(string:"http://chuadiv.ddns.net/easytoschool/fetch_book_detailed.php");
let request = NSMutableURLRequest(url:myUrl as! URL);
request.httpMethod = "POST";
let postString = "name=\(libro)&mail=\(UserDefaults.standard.object(forKey: "userEmail") as? String)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil{
print("error=\(error)")
return
}
var err: NSError?
do{
var json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray
if let parseJSON: NSArray = json{
for index in 0...parseJSON.count-1 {
print("ciao")
let libro = parseJSON[index] as! [String:Any]
print("\n\n",index,":\n")
let book = resultCell.init(bookId: libro["id"] as! String,bookName: libro["name"] as! String,bookAuthor: libro["author"] as! String,bookSchool: libro["school"] as! String,bookPrice: libro["price"] as! String,bookStatus: libro["status"] as! String,bookISBN: libro["isbn"] as! String,bookType: libro["type"] as! String,bookIdSeller: libro["idSeller"] as! String,bookNameSeller: libro["nameSeller"] as! String,bookSurnameSeller: libro["surnameSeller"] as! String)
book.printBook();
HomeViewController.booksArray.append(book)
}
}
}catch{
print("error=\(error)")
return
}
}
task.resume();
performSegue(withIdentifier: "homeToListBook", sender: self)
}
}else{
var myAlert = UIAlertController(title:"Attenzione\n", message:"Inserire solo numeri per la ricerca attraverso codice ISBN", preferredStyle:UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default){ action in }
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}
}
}
我希望当我按下按钮时它设置我的数组,然后它转到 tableView,但我不能
您正在将项目附加到另一个实例的数组,甚至附加到某个静态变量而不是传递它
您应该做的是创建 class of Book
的所有属性
class Book {
let id: String
init(data: [String:Any]) {
self.id = data["id"] as? String ?? "" //or some other error handling
}
}
然后在当前 UIViewController
中创建一个书籍数组
var books: [Book] = []
然后做类似的事情
let book = Book(data: libro)
books.append(book)
要传递数据,您应该在目标控制器中创建一个书籍数组 (HomeViewController
)
设置其 DataSource
和 Delegate
函数以使用此数组创建 UITableViewCells
并像
一样传递数据
override func prepare(for segue: UIStoryboardSegue, sender _: Any?) {
if segue.identifier == "homeToListBook" {
if let destinationVC = segue.destination as? HomeViewController {
destinationVC.books = self.books
}
}
}
编辑:
正如 Nirav D 提到的,在数据被解析后应该在主线程中调用 segue,没有注意到这个
问题是 dataTask
的完成块将调用异步,因此它稍后会调用,而您当前正在它的完成块之外执行 segue。所以你需要做的是在 dataTask
的完成块内调用 performSegue
也在 Main
线程上。还使用 URL
和 URLRequest
代替 NSURL
和 NS(Mutable)URLRequest
let myUrl = URL(string:"http://chuadiv.ddns.net/easytoschool/fetch_book_detailed.php")
let request = URLRequest(url:myUrl!)
request.httpMethod = "POST";
let postString = "name=\(libro)&mail=\(UserDefaults.standard.string(forKey: "userEmail")!)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil{
print("error=\(error)")
return
}
var err: NSError?
do{
var json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [[String:Any]]
if let parseJSON = json {
for libro in in parseJSON {
let book = resultCell.init(bookId: libro["id"] as! String,bookName: libro["name"] as! String,bookAuthor: libro["author"] as! String,bookSchool: libro["school"] as! String,bookPrice: libro["price"] as! String,bookStatus: libro["status"] as! String,bookISBN: libro["isbn"] as! String,bookType: libro["type"] as! String,bookIdSeller: libro["idSeller"] as! String,bookNameSeller: libro["nameSeller"] as! String,bookSurnameSeller: libro["surnameSeller"] as! String)
book.printBook();
HomeViewController.booksArray.append(book)
}
//Perform segue now
DispatchQueue.main.async {
performSegue(withIdentifier: "homeToListBook", sender: self)
}
}
}catch{
print("error=\(error)")
return
}
}
task.resume()
注意:在Swift中使用Swift原生类型数组和字典,而不是NSArray
和NSDictionary
。
我在我的应用程序的一部分中有此实现:
为什么当我点击 "cerca per ISBN" 按钮时它会转到 tableView 而没有执行我编写的说明?
这是我点击的 "cerca per ISBN" 按钮的代码:
@IBAction func ISBNButtonClick(_ sender: Any) {
let libro = Libro.text! as String
if Libro.text!.isEmpty {
//Alert per segnalare i campi mancanti, oltre a caselle rosse
var myAlert = UIAlertController(title:"Attenzione\n", message:"Inserire il codice ISBN", preferredStyle:UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default){ action in }
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
// placeholder rosso se la text è vuota
Libro.attributedPlaceholder = NSAttributedString(string:"Digita qui...", attributes: [NSForegroundColorAttributeName: UIColor.red])
//se tutti i campi obbligatori sono stati inseriti, proseguo ad altri controlli
}else{
if(isNumeric(string: libro)){
if((libro.characters.count) < 13 || (libro.characters.count) > 13){
//Alert per segnalare l'ISBN più corto di 13 numeri
var myAlert = UIAlertController(title:"Attenzione\n", message:"L'ISBN deve essere di 13 cifre", preferredStyle:UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default){ action in }
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}else{
//inviare dati al server
let myUrl = NSURL(string:"http://chuadiv.ddns.net/easytoschool/fetch_book_detailed.php");
let request = NSMutableURLRequest(url:myUrl as! URL);
request.httpMethod = "POST";
let postString = "name=\(libro)&mail=\(UserDefaults.standard.object(forKey: "userEmail") as? String)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil{
print("error=\(error)")
return
}
var err: NSError?
do{
var json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSArray
if let parseJSON: NSArray = json{
for index in 0...parseJSON.count-1 {
print("ciao")
let libro = parseJSON[index] as! [String:Any]
print("\n\n",index,":\n")
let book = resultCell.init(bookId: libro["id"] as! String,bookName: libro["name"] as! String,bookAuthor: libro["author"] as! String,bookSchool: libro["school"] as! String,bookPrice: libro["price"] as! String,bookStatus: libro["status"] as! String,bookISBN: libro["isbn"] as! String,bookType: libro["type"] as! String,bookIdSeller: libro["idSeller"] as! String,bookNameSeller: libro["nameSeller"] as! String,bookSurnameSeller: libro["surnameSeller"] as! String)
book.printBook();
HomeViewController.booksArray.append(book)
}
}
}catch{
print("error=\(error)")
return
}
}
task.resume();
performSegue(withIdentifier: "homeToListBook", sender: self)
}
}else{
var myAlert = UIAlertController(title:"Attenzione\n", message:"Inserire solo numeri per la ricerca attraverso codice ISBN", preferredStyle:UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"Ok", style:UIAlertActionStyle.default){ action in }
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}
}
}
我希望当我按下按钮时它设置我的数组,然后它转到 tableView,但我不能
您正在将项目附加到另一个实例的数组,甚至附加到某个静态变量而不是传递它
您应该做的是创建 class of Book
的所有属性
class Book {
let id: String
init(data: [String:Any]) {
self.id = data["id"] as? String ?? "" //or some other error handling
}
}
然后在当前 UIViewController
var books: [Book] = []
然后做类似的事情
let book = Book(data: libro)
books.append(book)
要传递数据,您应该在目标控制器中创建一个书籍数组 (HomeViewController
)
设置其 DataSource
和 Delegate
函数以使用此数组创建 UITableViewCells
并像
一样传递数据override func prepare(for segue: UIStoryboardSegue, sender _: Any?) {
if segue.identifier == "homeToListBook" {
if let destinationVC = segue.destination as? HomeViewController {
destinationVC.books = self.books
}
}
}
编辑: 正如 Nirav D 提到的,在数据被解析后应该在主线程中调用 segue,没有注意到这个
问题是 dataTask
的完成块将调用异步,因此它稍后会调用,而您当前正在它的完成块之外执行 segue。所以你需要做的是在 dataTask
的完成块内调用 performSegue
也在 Main
线程上。还使用 URL
和 URLRequest
代替 NSURL
和 NS(Mutable)URLRequest
let myUrl = URL(string:"http://chuadiv.ddns.net/easytoschool/fetch_book_detailed.php")
let request = URLRequest(url:myUrl!)
request.httpMethod = "POST";
let postString = "name=\(libro)&mail=\(UserDefaults.standard.string(forKey: "userEmail")!)"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil{
print("error=\(error)")
return
}
var err: NSError?
do{
var json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? [[String:Any]]
if let parseJSON = json {
for libro in in parseJSON {
let book = resultCell.init(bookId: libro["id"] as! String,bookName: libro["name"] as! String,bookAuthor: libro["author"] as! String,bookSchool: libro["school"] as! String,bookPrice: libro["price"] as! String,bookStatus: libro["status"] as! String,bookISBN: libro["isbn"] as! String,bookType: libro["type"] as! String,bookIdSeller: libro["idSeller"] as! String,bookNameSeller: libro["nameSeller"] as! String,bookSurnameSeller: libro["surnameSeller"] as! String)
book.printBook();
HomeViewController.booksArray.append(book)
}
//Perform segue now
DispatchQueue.main.async {
performSegue(withIdentifier: "homeToListBook", sender: self)
}
}
}catch{
print("error=\(error)")
return
}
}
task.resume()
注意:在Swift中使用Swift原生类型数组和字典,而不是NSArray
和NSDictionary
。