Использование API в Swift (Почтальон, Alamofire, SwiftyJson) - PullRequest
0 голосов
/ 28 апреля 2018

У меня есть админ-панель, в которую администратор может вставить вопрос и предоставить пользователям 3 варианта ответов. Администратор может вставлять вопросы в соответствии с различными главами ... это похоже на игру-викторину ... Правильному ответу присваивается значение типа int, поэтому в моей коллекции из 3 кнопок я могу узнать, какая кнопка у пользователя правильная. выбран. Но теперь моя проблема в моем почтальоне:

enter image description here

в моем быстром коде

   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
    ]

это объявление правильно?

что касается моей раскадровки: enter image description here

и после этого я буду делать

button1.setTitle = answer1
questionlabel.text = question

в моем файле swift для части, где я связываю свой API

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)
    }
}}

соответственно будут показаны мои данные ??

1 Ответ

0 голосов
/ 28 апреля 2018

После ответа 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)
})
...