使用字典swift将参数发布到服务器

时间:2016-12-26 08:39:19

标签: ios swift nsdictionary nsjsonserialization

我正在尝试使用字典将数据发送到服务器,但遗憾的是数据未保存到数据库(字段被发现为空白),我得到以下响应:

  

可选(["状态":true," msg":成功])

还尝试向用户展示UIActivityIndicator,直到他得到回复但无法找到方法。

尝试的代码:

let dict = [ "key_one": self.tf1.text!,"key_two":self.tf2.text!]

    do {

        let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted)

        // create post request
        let url = NSURL(string: "myAPIUrl.php?")!
        let request = NSMutableURLRequest(URL: url)
        request.HTTPMethod = "POST"

        // insert json data to the request
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.HTTPBody = jsonData

        let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
            if error != nil{
                print("Error -> \(error)")
                return
            }

            do {
                let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]

                print("Response -> \(result)")

            } catch {
                print("Inside Error Section -> \(error)")
            }
        }

        task.resume()

    } catch {
        print(error)
    }

1 个答案:

答案 0 :(得分:2)

//在一个fucantion中写这个

NSString* str = [[NSString alloc] initWithData:aNSData encoding:NSUTF8StringEncoding];