使用JSON和Swift从服务器接收数据

时间:2016-01-11 15:20:45

标签: json server ios9

我正在尝试将数据从我的应用程序发送到我的服务器,但现在我需要接收一些数据并放入数组。

这是我的代码:

//declare parameter as a dictionary which contains string as key and value combination

let parameters = ["marchio": newVettura.cognome, "user": newVettura.targa ] as Dictionary<String, String>

    //create the url with NSURL
    let url = NSURL(string: "http://parts.gibiauto.com/ciccio.php") //change the url

    //create the session object
    let 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

    let err: NSError?
    //request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err)
    request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options:[])// 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
    let task = session.dataTaskWithRequest(request) { data, response, error in
        guard data != nil else {
            print("no data found: \(error)")
            return
        }

        // this, on the other hand, can quite easily fail if there's a server error, so you definitely
        // want to wrap this in `do`-`try`-`catch`:

        do {
            if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                let success = json["success"] as? Int                                  // Okay, the `json` is here, let's get the value for 'success' out of it
                print("Success: \(success)")
            } else {
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)    // No error thrown, but not NSDictionary
                print("Error could not parse JSON: \(jsonStr)")
            }
        } catch let parseError {
            print(parseError)                                                          // Log the error thrown by `JSONObjectWithData`
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: '\(jsonStr)'")
        }
    }

    task.resume() }

现在,我如何记忆服务器发送给我的数组?

2 个答案:

答案 0 :(得分:0)

您正在寻找this part of the SDK。另一方面,您显然已经知道,因为您使用它来创建要传递的数据。

这留下了另一个答案:

向您的类添加实例变量以存储结果。当异步块被执行并且您对结果感到满意时,将其分配给实例变量。

答案 1 :(得分:0)

do{
  valuearray = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
  let json = try? JSONDecoder().decode(Encrypt.self, from: data!)
  print(json as Any)
  } catch let err as NSError { print(err) }
       for anItem in valuearray as! [Dictionary<String, AnyObject>] {
           let ascii_text = anItem["ascii_text"] as! String
           let random_text = anItem["random_text"] as! String
       }