2017-02-13 24 views
1

我有功能,低於該每用戶返回課程:響應是nil

func CoursesPerUser(controler: UIViewController, completionHandler: @escaping (Result<[Course]>) -> Void){ 

    Alamofire.request(Constants.API.Users + UserId() + Constants.API.CoursesPerUser + Token(), encoding: JSONEncoding.default).responseJSON { response in 

     guard response.result.error == nil else { 
      print(response.result.error!) 
      completionHandler(.failure(response.result.error!)) 
      return 
     } 

     guard let json = response.result.value as? [[String: AnyObject]] else { 
      print("Didn't get course objects as JSON from API") 
      completionHandler(.failure(BackendError.objectSerialization(reason: "Did not get JSON array in response"))) 
      return 
     } 

     var courses:[Course] = [] 
     for element in json { 
      if let courseResult = Course(json: element) { 
       courses.append(courseResult) 
      } 
     } 
     completionHandler(.success(courses)) 
    } 
} 

當我調用該函數響應具有零的值。

NetworkManager.sharedInstance.CoursesPerUser(controler: controler) { response in 

     print("Size of courses" + String(describing: response.value?.count)) 

} 

我打印函數CoursesPerUser中的每個元素,一切工作正常。我不知道我是不是以良好的態度處理結果。

+1

請將您的解決方案作爲答案發布,因爲別人可能會遇到此問題,並且如果您的解決方案是以答案的形式,它將更具可讀性。 – Miknash

回答

0

我已經解決了這個問題。解決方案如下。

func CoursesPerUser(completionHandler: @escaping ([Course]?, NSError?) ->()){ 

    Alamofire.request(Constants.API.Users + UserId() + Constants.API.CoursesPerUser + Token(), encoding: JSONEncoding.default).responseJSON { response in 

     switch response.result { 

     case .success : 


      if let result: AnyObject = response.result.value as AnyObject? { 

       if(response.response?.statusCode == 200){ 

        var courses:[Course] = [] 

        if let array = JSON(result).array { 

         for element in array { 

          if let course = Course(json: element) { 

           courses.append(course) 

          } 

         } 
        } 

        completionHandler(courses, nil) 

       } else { 

        if let message = JSON(result)["message"].string { 

         print("Logg: " + message) 

        } 
       } 

      } 

     case .failure(let error): 

      completionHandler(nil, error as NSError?) 
     } 
    } 
} 



NetworkManager.sharedInstance.CoursesPerUser() { courses, error in 

    if(error == nil) { 

     print("Size of courses" + String(describing: courses.count)) 

    } else { 

     print("Log: " + String(describing: error)) 

    } 

} 
相關問題