Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 在Swift中使用API(Postman、Alamofire、SwiftyJson)_Ios_Swift_Alamofire_Postman_Swifty Json - Fatal编程技术网

Ios 在Swift中使用API(Postman、Alamofire、SwiftyJson)

Ios 在Swift中使用API(Postman、Alamofire、SwiftyJson),ios,swift,alamofire,postman,swifty-json,Ios,Swift,Alamofire,Postman,Swifty Json,我有一个管理员面板,管理员可以插入问题,并提供3个选项的答案给用户选择。管理员可以根据不同的章节插入问题…这就像一个问答游戏。正确的答案会被赋予一个int值,因此在我的3个按钮集合中,我能够知道用户选择的是正确的按钮。但现在我的问题是,在我的邮递员身上: 在我的swift代码中 func getaQuestionaByaChapter(chapterName: String,question: String, answer1: String, answer2 : String, answ

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

在我的swift代码中

   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
在我的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)
    }
}}

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

在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?
}
然后,您必须解析模型数据中的响应:

然后在QuizViewController中:您必须设置数据:


您面临的问题我需要根据我在管理面板中设置的内容显示我的标签和按钮标题。正如你们所看到的,在我的《邮差》中,这是第二章,问题是10+10。方案一是10,方案二是20,方案三是30。正确答案是选项2,这意味着它是按钮[1],因为我在一个集合中放置了三个按钮。现在,在我的代码中,按钮标题和标签文本不显示。我不确定你为什么能给我看你的代码,检查后我会让你知道的好,让我试试…在这里粘贴代码?你可以将代码上传到Github,然后共享OK,这意味着我需要删除我的问题类文件,创建一个新的文件QuestionModel,然后声明函数,最后将数据设置为你的代码?是的,您可以尝试让我知道是否有任何东西卡住了。您已经编辑了代码,但在我的EduAppRestClient中,出现了一个错误,按钮显示它没有订阅成员??已提交并按下Github。TQ为了帮助从answerButtons中删除1,2,3,更新了我的答案,请检查以下错误:从模型数据中类型为“(,)throws->()”的抛出函数转换为非抛出函数类型“(JSON?,error?->Void”)无效
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)")
        }
    }
}}
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)
})