2015-09-26 12 views
12

Ho scritto questo codice (NSData ?, NSURLResponse ?, NSError?):conversione non valida dal funzione del tipo (_, _, _) gettando getta -> Vuoto a non gettare tipo di funzione -> Void

func getjson() { 
     let urlPath = "https://api.whitehouse.gov/v1/petitions.json?limit=100" 
     let url = NSURL(string: urlPath) 
     let session = NSURLSession.sharedSession() 
     let task = session.dataTaskWithURL(url!, completionHandler: {data, response, error -> Void in 
      print("Task completed") 
      if(error != nil) { 
       print(error!.localizedDescription) 
      } 
      let err: NSError? 
      if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary { 
       if(err != nil) { 
        print("JSON Error \(err!.localizedDescription)") 
       } 
       if let results: NSArray = jsonResult["results"] as? NSArray { 
        dispatch_async(dispatch_get_main_queue(), { 
         self.tableData = results 
         self.Indextableview.reloadData() 
        }) 
       } 
      } 
     }) 

     task.resume() 

    } 

E dopo l'aggiornamento a XCode 7 mi dà questo errore: Conversione non valida dalla funzione di lancio di tipo (_, _, _) genera -> Void a tipo di funzione non di lancio (NSData?, NSURLResponse?, NSError?) - > Vuoto. È in linea, dove è lascia compito.

Grazie

+0

punto la linea che causa il problema e aggiornare la tua domanda con il messaggio di errore completo ed esatto. – rmaddy

+0

Devi usare provare! o implementare provare a catturare –

+0

Ma dove dovrei provare? @LeoDabus –

risposta

26

È necessario implementare Do Prova errore Cattura gestione come segue:

func getjson() { 
    let url = NSURL(string: "https://api.whitehouse.gov/v1/petitions.json?limit=100")! 
    let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in 
     print("Task completed") 
     if let data = data { 
      do { 
       if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary { 
        dispatch_async(dispatch_get_main_queue(), { 

         if let results: NSArray = jsonResult["results"] as? NSArray { 
          self.tableData = results 
          self.Indextableview.reloadData() 
         } 
        }) 

       } 
      } catch let error as NSError { 
       print(error.localizedDescription) 
      } 
     } else if let error = error { 
      print(error.localizedDescription) 
     } 
    } 
    task.resume() 
} 
+0

Grazie ora funziona bene –

+0

@MartinMikusovic sei il benvenuto –

+1

C'è un modo per consegnare l'errore più in alto sulla catena ? Perché la mia funzione "getjson" è in una classe separata. E non voglio stampare la descrizione dell'errore ma mostrarlo all'utente in un UIAlertController. Ma UIAlertController può essere mostrato solo da un UIViewController con chiamate "getjson". – Adarkas2302

0

Come suggerito Leo, il problema è che si sta utilizzando try, ma non all'interno del do - try - catch costrutto, il che significa che deduce che la chiusura è definita per lanciare l'errore, ma poiché non è definita come tale, si ottiene quell'errore.

Quindi, aggiungere do - try-catch:

func getjson() { 
    let urlPath = "https://api.whitehouse.gov/v1/petitions.json?limit=100" 
    let url = NSURL(string: urlPath) 
    let session = NSURLSession.sharedSession() 
    let task = session.dataTaskWithURL(url!) { data, response, error in 
     print("Task completed") 

     guard data != nil && error == nil else { 
      print(error?.localizedDescription) 
      return 
     } 

     do { 
      if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary { 
       if let results = jsonResult["results"] as? NSArray { 
        dispatch_async(dispatch_get_main_queue()) { 
         self.tableData = results 
         self.Indextableview.reloadData() 
        } 
       } 
      } 
     } catch let parseError as NSError { 
      print("JSON Error \(parseError.localizedDescription)") 
     } 
    } 

    task.resume() 
} 
0

In Swift 2, sostituire tutti i NSError con ErrorType

Prova questa.

class func fetchWeatherForLocation(locationCode: String = "", shouldShowHUD: Bool = false, completionHandler: (data: NSDictionary?, error: ErrorType?) ->()) { 



    let url = NSURL(string: "myurl")    
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in 

     if let dataWithKey = data { 

      do { 
       let jsonForDataWithTemprature = try NSJSONSerialization.JSONObjectWithData(dataWithKey, options:NSJSONReadingOptions.MutableContainers) 

       guard let arrayForDataWithKey :NSArray = jsonForDataWithTemprature as? NSArray else { 
        print("Not a Dictionary") 
        return 
       } 

       let dictionaryWithTemprature = arrayForDataWithKey.firstObject as! NSDictionary 

       completionHandler(data: dictionaryWithTemprature, error: nil) 

      } 
      catch let JSONError as ErrorType { 
       print("\(JSONError)") 
      } 

     } 
    } 

    task.resume() 
} 
0

La modifica del tipo di errore nel codice try-catch ha funzionato per me.

"Sostituire tutte NSError con ERRORE.TIPO"

Problemi correlati