我有以下功能,每位用户返回课程:
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))
}
}
当我调用函数时,响应的值为nil。
NetworkManager.sharedInstance.CoursesPerUser(controler: controler) { response in
print("Size of courses" + String(describing: response.value?.count))
}
我在函数CoursesPerUser中打印了每个元素,一切正常。我想知道我是不是以良好的方式处理结果。
答案 0 :(得分: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))
}
}