【问题标题】:How to create and send the json data to server using swift language如何使用 swift 语言创建 json 数据并将其发送到服务器
【发布时间】:2015-02-23 14:43:33
【问题描述】:

我是 IOS 开发的新手,我已经开始使用 swift 语言。

我正在尝试从两个文本字段中获取值并将这两个文本字段转换为 json 并将该 json 发送到服务器 receive.php。

让我们认为两个文本字段是 - 姓名 - 通过

如何创建 Json 并在单击按钮时将其发送到服务器?

【问题讨论】:

标签: ios json swift xcode6 swift-playground


【解决方案1】:

通过使用带有 NSURLSession 的 http POST 方法。假设您在按下登录按钮时调用 submitAction 方法

斯威夫特 3

@IBAction func submitAction(_ sender: UIButton) {

    //declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid

    let parameters: [String: String] = ["name": nametextField.text, "password": passwordTextField.text]

    //create the url with URL
    let url = URL(string: "http://myServerName.com/api")! //change the url

    //create the session object
    let session = URLSession.shared

    //now create the URLRequest object using the url object
    var request = URLRequest(url: url)
    request.httpMethod = "POST" //set http method as POST

    do {
        request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body

    } catch let error {
        print(error.localizedDescription)
    }

    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    //create dataTask using the session object to send data to the server
    let task = session.dataTask(with: request, completionHandler: { data, response, error in

        guard error == nil else {
            return
        }

        guard let data = data else {
            return
        }

        do {
            //create json object from data
            if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                print(json)
                // handle json...
            }

        } catch let error {
            print(error.localizedDescription)
        }
    })
    task.resume()
}

【讨论】:

    【解决方案2】:

    斯威夫特 3,斯威夫特 4 上面的方法效率很低,改用alamofire吧

    https://github.com/Alamofire/Alamofire

    从文本字段中获取电子邮件和密码

    @IBAction func submitAction(sender: AnyObject) {
    let email= emailfield.text
    let password= emailfield.text
    let parameters: Parameters = [
        "email": email,
        "password": password
        ]
    
    Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters) }
    

    或者这里是一个例子

    let parameters: Parameters = [
    "foo": "bar",
    "baz": ["a", 1],
    "qux": [
        "x": 1,
        "y": 2,
        "z": 3
    ]
    ]
    
    // All three of these calls are equivalent
    Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters)
    Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default)
    Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)
    
    // HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
    

    【讨论】:

      【解决方案3】:

      对于那些无法让Alamofire.request 工作的人,请使用AF 而不是Alamofire。例如:

      AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
      

      来自docs

      Alamofire 文档的早期版本使用了类似的示例 Alamofire.request()。这个 API,虽然它似乎需要 Alamofire 前缀,实际上没有它也能正常工作。请求方法 和其他功能在任何文件中全局可用的导入 阿拉莫菲尔。从 Alamofire 5 开始,此功能已 删除,而是 AF 全局是对 Session.default 的引用。 这允许 Alamofire 提供相同的便利功能 而不必每次 Alamofire 都污染全局命名空间 使用,而不必在全球范围内复制 Session API。 同样,由 Alamofire 扩展的类型将使用 af 属性 将 Alamofire 添加的功能与其他功能分开的扩展 扩展。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-10-03
        • 1970-01-01
        • 2011-09-16
        • 1970-01-01
        • 1970-01-01
        • 2019-06-14
        • 2015-10-18
        相关资源
        最近更新 更多