0

我真的需要一个使用 JSON 从服务器发送和接收数据的代码,我找到了一个非常好的代码,但它与 iOS9 不兼容。

@IBAction func submitAction(sender: AnyObject) {

            //declare parameter as a dictionary which contains string as key and value combination.
            var parameters = ["name": nametextField.text, "password": passwordTextField.text] as Dictionary<String, String>

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

            //create the session object 
            var session = NSURLSession.sharedSession()

            //now create the NSMutableRequest object using the url object
            let request = NSMutableURLRequest(URL: url!)
             request.HTTPMethod = "POST" //set http method as POST

            var err: NSError?
            request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err) // pass dictionary to nsdata object and set it as request body

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

                // 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)'")
                }
                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
                        var success = parseJSON["success"] as? Int
                        println("Succes: \(success)")
                    }
                    else {
                        // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
                        let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
                        println("Error could not parse JSON: \(jsonStr)")
                    }
                }
            })

            task.resume() }

真的感谢您的帮助

4

2 回答 2

0

也许看看 Alamofire 框架。在处理 HTTP 请求时,它确实让您的生活更轻松。

否则,正如 vadian 建议的那样,请查看 Swift 2 (do-try-catch) 错误处理。

我从 deege 找到了一个很棒的教程项目。

https://github.com/deege/deegeu-swift-rest-example

这里是一个 HTTP 请求的细分。

    // Setup the session to make REST GET call.  Notice the URL is https NOT http!! (if you need further assistance on how and why, let me know)
    let endpoint: String = "https://yourAPI-Endpoint"
    let session = NSURLSession.sharedSession()
    let url = NSURL(string: endpoint)!

     // Make the call and handle it in a completion handler
    session.dataTaskWithURL(url, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
        // Make sure we get an OK response
        guard let realResponse = response as? NSHTTPURLResponse where
                  realResponse.statusCode == 200 else {
            print("Not a 200 response")
                    return
        }

        // Read the JSON
        do {
            if let jsonString = NSString(data:data!, encoding: NSUTF8StringEncoding) {
                // Print what we got from the call
                print(jsonString)

                // Parse the JSON
                let jsonDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary

                let value = jsonDictionary["key"] as! String
            }
        } catch {
            print("bad things happened")
        }
    }).resume()
于 2016-01-10T20:56:58.710 回答
0

Swift 语法稍有改变,但并没有显着破坏整个代码。

你需要调整一些东西,比如

println(err!.localizedDescription)

print(err!.localizedDescription)

然后你的代码将编译

于 2016-01-10T21:00:30.453 回答