将JSON数据发送到服务器?

时间:2015-08-12 04:07:53

标签: ios json xcode swift post

我在我的app delegate中有这段代码:

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    // Override point for customization after application launch.
    self.post(["data":"tes"], url: "pandubaraja.esy.es/test.php") { (succeeded: Bool, msg: String) -> () in
        var alert = UIAlertView(title: "Success!", message: msg, delegate: nil, cancelButtonTitle: "Okay.")
        if(succeeded) {
            alert.title = "Success!"
            alert.message = msg
        }
        else {
            alert.title = "Failed :("
            alert.message = msg
        }

        // Move to the UI thread
        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            // Show the alert
            alert.show()
        })
    }
    return true
}

func post(params : Dictionary<String, String>, url : String, postCompleted : (succeeded: Bool, msg: String) -> ()) {
    var request = NSMutableURLRequest(URL: NSURL(string: "pandubaraja.esy.es/test.php")!)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        println("Response: \(response)")
        var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("Body: \(strData)")
        var err: NSError?
        var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

        var msg = "No message"

        // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
        if(err != nil) {
            println(err!.localizedDescription)
            let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("Error could not parse JSON: '\(jsonStr)'")
            postCompleted(succeeded: false, msg: "Error")
        }
        else {
            // The JSONObjectWithData constructor didn't return an error. But, we should still
            // check and make sure that json has a value using optional binding.
            if let parseJSON = json {
                // Okay, the parsedJSON is here, let's get the value for 'success' out of it
                if let success = parseJSON["success"] as? Bool {
                    println("Succes: \(success)")
                    postCompleted(succeeded: success, msg: "Logged in.")
                }
                return
            }
            else {
                // Woa, okay the json object was nil, something went wrong. Maybe the server isn't running?
                let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                println("Error could not parse JSON: \(jsonStr)")
                postCompleted(succeeded: false, msg: "Error")
            }
        }
    })

    task.resume()
}
当我点击一个按钮时,

andIi已经有了数据,它显示在控制台(println)上,但我仍然混淆了如何将它发送到服务器

这是用于发送数据的代码,或者您可以说,在控制台上打印数据

    import UIKit


class SendData: UIViewController, PiechartDelegate{

    @IBOutlet weak var Kirim: UIImageView!


    var total: CGFloat = 40
    func tapGesture(gesture: UIGestureRecognizer) {
        if let Kirim = gesture.view as? UIImageView {  // if you subclass UIImageView, then change "UIImageView" to your subclass
            println(personaldata.data)


            for (var i = 0; i < Nutritionmenu.data.count; i++) {
                println(Nutritionmenu.data[i]);
            }
            for (var i = 0; i < Activitymenu.dataact.count; i++) {
                println(Activitymenu.dataact[i]);
            }
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        let tapGesture = UITapGestureRecognizer(target: self, action: "tapGesture:")
        Kirim.addGestureRecognizer(tapGesture)
        Kirim.userInteractionEnabled = true

this is the data that i want to send to the server

这是我想要发送到服务器的数据但是当我编译时,它总是说错误而不是成功!

0 个答案:

没有答案