In this new swift 2 tutorial you'll learn how to parse json data structure in order to send complex data structure as a String to an external server. You'll see how to prepare the array of objects to send and how to do the data parsing into the json format. In the second part of this tutorial, you'll see how to extract the json data by using the NSDictionary and NSArray data type.
Configure the project
Open Swift and create a new iOS single view app. In this example the http protocol is used in order to send and receive the data from this protocol, in swift 2 you'll need to enable it. Search for the info.plist file, right click on it, choose open as - source code and add the following lines.
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> </dict>
Json parsing: let's parse and send the json data to an external server
You'll see now how to parse a data structure and send it as a json String to an external server. In this example we'll send an object with the following structure: request - [string name of the request] ; some_extra_data - [string with the extra data]
Once the data is parsed as a json element, you'll able to send it as a string to the server. In this example I've prepared a simple server side script that get the posted data and just reply it out. Let's open the ViewController.swift file and define the send_and_parse_json function.
func send_and_parse_json() { var send_data:[String:String] = [String:String]() send_data["request"] = "kaleidosblog" send_data["some_extra_data"] = "1" do { let json = try NSJSONSerialization.dataWithJSONObject(send_data, options: NSJSONWritingOptions(rawValue: 0)) let data_string = NSString(data: json, encoding:NSUTF8StringEncoding) data_request(data_string!) } catch { } }
Using the NSJSONSerialization swift function, you'll able to convert your data structure into the json data format. Now you'll able to send it to your server. Let's implement the data_request function, that will send the json object to your server.
func data_request(data:NSString) { let url_to_request = "https://www.kaleidosblog.com/tutorial/get_data.php" let url:NSURL = NSURL(string: url_to_request)! let session = NSURLSession.sharedSession() let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "POST" request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData request.timeoutInterval = 10 let paramString = "data=" + (data as String) request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding) let task = session.dataTaskWithRequest(request) { ( let data, let response, let error) in guard let _:NSData = data, let _:NSURLResponse = response where error == nil else { print("error") return } let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding) print(dataString) } task.resume() }
We'll send a post request and the json data string are defined inside the data post variable. The echo from the server is then printed using the print swift function.
Json extraction: let's extract json data sent from a server using the NSDictionary and NSArray
In this second section of the tutorial you'll see how to receive json data structure and how to extract it inside a swift array. In this example you'll see the following data structure:
object [colorsArray]
Array []
object[colorName]
object[hexValue]
Let's first asynchronously download the data from the server using the NSURLSession swift function.
func get_json_data() { let url_to_request = "https://www.kaleidosblog.com/tutorial/colors.json" let url:NSURL = NSURL(string: url_to_request)! let session = NSURLSession.sharedSession() let request = NSMutableURLRequest(URL: url) request.HTTPMethod = "GET" request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData request.timeoutInterval = 10 let task = session.dataTaskWithRequest(request) { ( let data, let response, let error) in guard let _:NSData = data, let _:NSURLResponse = response where error == nil else { print("error") return } self.extract_json_data(data!) } task.resume() }
The guard function has been used to check the right data format. As soon as the data is received, the extract_json_data function is called.
func extract_json_data(data:NSData) { var json: AnyObject? do { json = try NSJSONSerialization.JSONObjectWithData(data, options: []) } catch { return } guard let data_dictionary = json as? NSDictionary else { return } guard let data_array = data_dictionary["colorsArray"] as? NSArray else { return } for(var i = 0; i < data_array.count; i++) { colors.append(Color(data: data_array[i] as! NSDictionary)) } print(colors) }
By following the data structure, we'll need to ensure that the data structure follows the right data formats:
object [colorsArray] [NSDictionary]
Array [] [NSArray]
object[colorName] [NSDictionary]
object[hexValue] [NSDictionary]
Let's define now the colors data structure.
var colors:[Color] = [Color]() struct Color { var name:String = "" var hex:String = "" init(data:NSDictionary) { if let add = data["colorName"] as? String { self.name = add } if let add = data["hexValue"] as? String { self.hex = add } } }
Download the complete example for swift 2 from here.
Leave a comment