【问题标题】:Using API in Swift (Postman,Alamofire,SwiftyJson)在 Swift 中使用 API (Postman,Alamofire,SwiftyJson)
【发布时间】:2018-04-28 18:35:35
【问题描述】:

我有一个管理面板,管理员可以插入问题并为用户提供 3 个答案选项以供选择。管理员能够根据不同的章节插入问题......就像一个问答游戏......正确的答案然后被赋予一个 int 值,所以在我的 3 个按钮集合中,我能够知道哪个是正确的按钮用户有选择。但现在我的问题是,在我的邮递员中:

在我的快速代码中

   func getaQuestionaByaChapter(chapterName: String,question: String, answer1: String, answer2 : String, answer3: String, answer: Int, completion: @escaping (JSON?, Error?) -> Void) {
    let parameters: [String : Any] = [
        "secret_key" : "b3370e1590a2cf2b430e8cf8a8b361bd",
        "_action" : "GETQUESTIONBYCHAPTER",
        "GETQUESTIONBYCHAPTER" : chapterName,
        "question" : question,
        "option1" : answer1,
        "option2" : answer2,
        "option3" : answer3,
        "answer" : answer
    ]

这是一个正确的声明吗?

至于我的故事板:

在这之后,我会做

button1.setTitle = answer1
questionlabel.text = question

在我链接 API 的部分的 swift 文件中

import SwiftyJSON
import Alamofire

public class  EduappRestClient {

enum ContentType: String {
    case json = "application/json"
    case jpeg = "image/jpeg"
    case formEncoded = "application/x-www-form-urlencoded"
    case none = "" //Content type will be empty
}

private static let url: URL = URL(string: "http://192.168.0.127:81/project/Online_Question/API/actiona")! //NSURL depreciated now using URL)

//singleton
static let sharedClient: EduappRestClient = EduappRestClient()

class func request(with url: URL,
                   method: HTTPMethod = .get,
                   parameters: Parameters? = nil,
                   contentType: ContentType = .json,
                   encoding: ParameterEncoding = JSONEncoding.default,
                   additionalHeaders: [String: String] = [:],
                   completion: @escaping(JSON?, Error?) -> Void
    ) {

    //MARK: Configure Headers
    var headers: [String: String] = [:]

    //if contenttype is specified as none type, leave content-type header field empty
    if contentType != .none {
        headers["Content-Type"] = contentType.rawValue

    }
    for (key, value) in additionalHeaders {
        headers[key] = value
    }

    Alamofire.request(url, method: method, parameters: parameters, encoding: encoding, headers: headers).responseJSON(completionHandler: { (response) in
        guard response.result.error == nil, let value = response.result.value else {
            completion(nil, response.result.error)
            return
        }

        let jsonData = JSON(value)
        completion(jsonData, nil)
    })
}

//MARK: - Getting questions by chapters
func getaQuestionaByaChapter(chapterName: String,question: String, answer1: String, answer2 : String, answer3: String, answer: Int, completion: @escaping (JSON?, Error?) -> Void) {
    let parameters: [String : Any] = [
        "secret_key" : "b3370e1590a2cf2b430e8cf8a8b361bd",
        "_action" : "GETQUESTIONBYCHAPTER",
        "GETQUESTIONBYCHAPTER" : chapterName,
        "question" : question,
        "option1" : answer1,
        "option2" : answer2,
        "option3" : answer3,
        "answer" : answer
    ]

    let URLString = EduappRestClient.url

    EduappRestClient.request(with: URLString, method: .post, parameters: parameters) { (json, error) in
        guard error == nil, let json = json else {
            completion(nil, error)
            return
        }

        let result: JSON = json[1]

        //result will print
        //"question": [
        // {
        //"question": "10+10",
        //"chapter_name": "Chapter 2",
        //"option1": "10",
        //"option2": "20",
        //"option3": "30",
        //"answer": "20"
        //}
        //]
        completion(result, nil)
    }
}}

它会相应地显示我的数据??

【问题讨论】:

  • 你遇到了什么问题
  • 我需要根据我在管理面板中设置的内容显示我的标签和按钮标题。如您所见,在我的邮递员中,这是第 2 章,问题是 10+10。选项一是 10,二是 20,选项三是 30。正确答案是选项 2,这意味着它是按钮 [1],因为我在一个集合中放置了三个按钮。现在,从我的代码中,按钮标题和标签文本没有显示。我不确定为什么
  • 你能不能把你的代码给我看看,我会告诉你的
  • 好的,让我试试...在这里粘贴 cmets 中的代码?
  • 你可以把你的代码上传到Github然后分享

标签: ios swift alamofire postman swifty-json


【解决方案1】:

API响应后,必须使用。

class QuestionModel: Codable {
    let questions: [Details]
}

class Details: Codable {
    let question: String?
    let chapter_name: String?
    let option1: Int?
    let option2: Int?
    let option3: Int?
}

然后,你必须解析模型数据中的响应:

func getaQuestionaByaChapter(chapterName: String, completion: @escaping (QuestionModel?, Error?) -> Void) {
    let parameters: [String : Any] = [
        "secret_key" : "b3370e1590a2cf2b430e8cf8a8b361bd",
        "_action" : "GETQUESTIONBYCHAPTER",
        "GETQUESTIONBYCHAPTER" : chapterName
    ]
    let URLString = EduappRestClient.url

    EduappRestClient.request(with: URLString, method: .post, parameters: parameters) { (json, error) in
        guard error == nil, let json = json else {
            completion(nil, error)
            return
        }
        do {
            let jsonData = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted)
            let result = try JSONDecoder().decode(QuestionModel.self, from: jsonData)
            completion(result, nil)
        } catch let message {
            print("JSON serialization error:" + "\(message)")
        }
    }
}}

然后在 QuizViewController 中:你要设置数据:

EduappRestClient.sharedClient.getaQuestionaByaChapter(chapterName: "Chapter 2", completion: { (response, error) in

    //json is the result from rest client

   let firstQuestion = response?.questions.first
    self.questionsLabel.text = firstQuestion?.question
    self.answerButtons.setTitle("\(firstQuestion?.option1)", for: UIControlState.normal)
    self.answerButtons.setTitle("\(firstQuestion?.option2)", for: UIControlState.normal)
    self.answerButtons.setTitle("\(firstQuestion?.option3)", for: UIControlState.normal)
})

【讨论】:

  • 好的,这意味着我需要删除我的问题类文件,创建一个新文件 QuestionModel,然后声明函数并最后将数据设置为您的代码?
  • 是的,您可以尝试让我知道是否有任何问题。
  • 已编辑代码,但在我的 EduAppRestClient 中,出现错误,并且按钮显示它没有下标成员?已提交并推送到 Github。 TQ 非常愿意帮忙
  • 从 answerButtons 中移除 1,2,3,更新我的答案,请查收
  • 有一个错误写道:从'(_, _) throws -> ()' 类型的抛出函数到非抛出函数类型'(JSON?, Error?) -> 的无效转换我的模型数据中的“无效”
猜你喜欢
  • 2023-03-18
  • 1970-01-01
  • 2014-12-27
  • 1970-01-01
  • 2015-04-18
  • 1970-01-01
  • 1970-01-01
  • 2018-11-12
  • 1970-01-01
相关资源
最近更新 更多