swift 为什么Alamofire删除请求不起作用?

ovfsdjhp  于 2023-01-25  发布在  Swift
关注(0)|答案(1)|浏览(117)

这里是我删除特定帖子的地方。到目前为止,我的所有帖子和获取请求都正常工作。这是API规范:https://github.com/cuappdev/ios-course-messageboard#delete-postspost_id

static func deletePost(id: Int, poster: String, completion: @escaping(Post) ->   Void) {
    let endpoint = "\(host)posts/\(id)"
    let parameters: [String: Any] = [
        "poster" : poster
    ]
        AF.request(endpoint, method: .delete, parameters: parameters, encoding: JSONEncoding.default).validate().responseData { (response) in

        switch response.result {
        case .success(let data):

            let jsonDecoder = JSONDecoder()

            // get the userResponse
            if let userResponse = try? jsonDecoder.decode(Post.self, from: data) {
                completion(userResponse)
            }

        case .failure(let error):
            print(error.localizedDescription)
        }
    }
    
}

static func getAllPosts(completion: @escaping ([Post]) -> Void) {
    let endpoint = "\(host)posts/"
    
    AF.request(endpoint, method: .get).validate().responseData { response in
        switch response.result {
        case .success(let data):
            let jsonDecoder = JSONDecoder()
            // get the userResponse
            
            if let userResponse = try? jsonDecoder.decode(Posts.self, from: data) {
                completion(userResponse)
            }
            break
        case .failure(let error):
            print(error.localizedDescription)
            break
        }
    }
    
}
epfja78i

epfja78i1#

可以使用下面的代码段。

static func deletePost(id: Int, poster: String, completion: @escaping(Post) ->   Void) {
   let endpoint = "\(host)posts/\(id)"
   let parameters: [String: Any] = [
       "poster" : poster,
      "_method" : "DELETE"
   ]

   AF.request(endpoint, method: .delete, parameters: parameters, encoding: JSONEncoding.default).validate().responseData { (response) in

    switch response.result {
    case .success(let data):

        let jsonDecoder = JSONDecoder()

        // get the userResponse
        if let userResponse = try? jsonDecoder.decode(Post.self, from: data) {
            completion(userResponse)
        }

    case .failure(let error):
        print(error.localizedDescription)
    }
}

相关问题