2017-05-13 44 views
0

我有我的應用程序的一部分,這個實施後:無法從視圖去另一個做一些說明

爲什麼當我點擊「CERCA每ISBN」按鈕,它進入的tableView沒有做我寫的說明?

這是「CERCA每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後,但我可以「T

回答

0

問題是,dataTask的完成塊將調用異步,以便稍後調用,並且當前正在其完成塊之外執行segue。所以你需要做的就是在Main線程的dataTask的完成塊內調用performSegue。還使用URLURLRequest代替NSURLNS(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本地類型陣列和詞典,而不是NSArrayNSDictionary

+0

我寫了你的代碼部分,但它不起作用。它會立即轉到另一個視圖而不打印「if part」 – Marco

+0

在另一個視圖中,我想先打印數組,但它告訴「索引超出範圍」;我認爲這是因爲它立即進入視圖沒有設置數組 – Marco

+0

而我在我的應用的另一部分有這種錯誤 – Marco

0

要附加項目到另一個實例的數組,甚至一些靜止無功而不是通過它

你應該做的是創建類的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 a ND 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應當在主線程數據被解析之後稱爲,沒有注意到這個