2016-10-02 46 views
0

我是Swift和iOS開發新手,但我試圖下載和分析存儲在MySQL數據庫中的數據。爲什麼我得到錯誤「域= NSCocoaErrorDomain代碼= 3840」沒有值。「 UserInfo = {NSDebugDescription =沒有值。}'?

我不斷收到錯誤:

Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}

我已張貼下面我的代碼,但我不認爲這個問題是在parseJSON功能,而是在數據的實際下載,當我打印'data'返回'<>'。

這裏是我的代碼:

//properties 

weak var delegate: HomeModelProtocal! 

var data : NSMutableData = NSMutableData() 

let urlPath: String = "http://localhost/service.php" //this will be changed to the path where service.php lives 

// Function to download the incoming JSON data 
func downloadItems(){ 
    let url: URL = URL(string: urlPath)! 
    var session: URLSession! 
    let configuration = URLSessionConfiguration.default 


    session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil) 

    let task = session.dataTask(with: url) 

    task.resume() 
} 

func urlSession(_ session: URLSession, task: URLSessionDataTask, didCompleteWithError error: Error?) { 
    self.data.append(data as Data) 
} 

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { 
    if error != nil{ 
     print("Failed to download data") 
    }else{ 
     print("Data downloaded") 
     print(data) 
     self.parseJSON() 
    } 
} 

func parseJSON(){ 

    var jsonResult: NSMutableArray = NSMutableArray() 

    do{ 
     jsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options: []) as! NSMutableArray 
    } catch let error as NSError { 
     print("**** sake its happened again \(error)") 
    } 

    var jsonElement: NSDictionary = NSDictionary() 
    let locations: NSMutableArray = NSMutableArray() 

    for i in 0 ..< jsonResult.count{ 
     jsonElement = jsonResult[i] as! NSDictionary 

     let location = LocationModel() 

     //the following insures none of the JsonElement values are nil through optional binding 
     if let exerciseName = jsonElement["stationName"] as? String, 
      let bodyPart = jsonElement["buildYear"] as? String 
     { 
      print(exerciseName, bodyPart) 
      location.exerciseName = exerciseName 
      location.bodyPart = bodyPart 

     } 

     locations.add(location) 

    } 

    DispatchQueue.main.async(execute: {() -> Void in 

     self.delegate.itemsDownloaded(items:locations) 

    }) 
} 
+0

也許反應是空的?你的'print(data)'顯示了什麼? –

+0

嘗試這樣做,在郵遞員或其他地方,並檢查,如果事情是真的有 –

+0

我試圖打印數據,並將其返回<> 當我查看我使用的網址我得到這個返回: 「[ { 「Exercise_Id」:「1」, 「Exercise_Name」:「Barbell Curl」, 「Body_Part」:「Arms」 },' – MHDev

回答

1

在你的代碼特別糟糕的事情:

//This method is not being called... 
func urlSession(_ session: URLSession, task: URLSessionDataTask, didCompleteWithError error: Error?) { 
    self.data.append(data as Data) //<-This line adding self.data to self.data 
} 

沒有urlSession(_:task:didCompleteWithError:)方法,這需要URLSessionDataTask作爲其第二個參數。所以,這個方法永遠不會被調用。

而且裏面的方法,self.data附加到self.data,所以即使被調用的方法,self.data仍然是空的......

您需要實現此方法改爲:

func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) { 
    self.data.append(data) 
} 

但是,如果除了累積收到的數據之外您不想做其他事情,則無需使用代理。

並且使用的是被迫鑄造在parseJSON()方法:

jsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options: []) as! NSMutableArray 

不指定.mutableContainers選項。這也會導致你的應用程序崩潰。

而你的代碼使用太多的NSSomethings


與所有這些事情的固定,就可以得到這樣的事情:

//properties 

weak var delegate: HomeModelProtocal! 

let urlPath: String = "http://localhost/service.php" //this will be changed to the path where service.php lives 

// Function to download the incoming JSON data 
func downloadItems() { 
    let url: URL = URL(string: urlPath)! 
    let session = URLSession.shared 

    let task = session.dataTask(with: url) {data, response, error in 
     if let error = error { 
      print("Failed to download data: \(error)") 
     } else if let data = data { 
      print("Data downloaded") 
      print(data as NSData) 
      //print(String(data: data, encoding: .utf8)) 
      self.parseJSON(data: data) 
     } else { 
      print("Something is wrong...") 
     } 
    } 

    task.resume() 
} 

func parseJSON(data: Data){ 

    do { 
     if let jsonResult = try JSONSerialization.jsonObject(with: data) as? [[String: AnyObject]] { 

      var locations: [LocationModel] = [] 

      for jsonElement in jsonResult { 
       let location = LocationModel() 

       //the following insures none of the JsonElement values are nil through optional binding 
       if let exerciseName = jsonElement["stationName"] as? String, 
        let bodyPart = jsonElement["buildYear"] as? String 
       { 
        print(exerciseName, bodyPart) 
        location.exerciseName = exerciseName 
        location.bodyPart = bodyPart 

       } 

       locations.append(location) 

       DispatchQueue.main.async { 
        self.delegate.itemsDownloaded(items: locations) 
       } 
      } 
     } else { 
      print("bad JSON") 
     } 
    } catch let error as NSError { 
     print("**** sake its happened again \(error)") 
    } 
} 
+0

非常感謝您幫助解決我的問題, – MHDev

相關問題