【问题标题】:Create and send json data to server using swift language and iOS 9+使用 swift 语言和 iOS 9+ 创建和发送 json 数据到服务器
【发布时间】:2016-01-10 11:11:14
【问题描述】:

我真的需要一个代码来使用 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() }

非常感谢您的帮助

【问题讨论】:

  • 使用Menu Edit &gt; Convert &gt; To Latest Swift Syntax将代码转换为Swift 2并阅读Swift语言指南中关于Error Handling的章节

标签: ios json server ios9 ios9.2


【解决方案1】:

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

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

println(err!.localizedDescription)

print(err!.localizedDescription)

然后你的代码将编译

【讨论】:

    【解决方案2】:

    也许看看 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()
    

    【讨论】:

    • 如果可以的话,请给我写一个管理错误的例子。非常感谢 =)
    猜你喜欢
    • 2015-02-23
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多