Tôi có một tệp JSON, muốn phân tích cú pháp và sử dụng danh sách các đối tượng trong chế độ xem bảng. Có ai có thể chia sẻ mã để phân tích cú pháp tệp JSON nhanh chóng không.
Tôi có một tệp JSON, muốn phân tích cú pháp và sử dụng danh sách các đối tượng trong chế độ xem bảng. Có ai có thể chia sẻ mã để phân tích cú pháp tệp JSON nhanh chóng không.
Câu trả lời:
Không thể đơn giản hơn:
import Foundation
let jsonData: Data = /* get your json data */
let jsonDict = try JSONSerialization.jsonObject(with: jsonData) as? NSDictionary
Điều đó đang được nói, tôi thực sự khuyên bạn nên sử dụng các API có thể mã hóa được giới thiệu trong Swift 4.
let jsonData = NSData.dataWithContentsOfFile(filepath, options: .DataReadingMappedIfSafe, error: nil)
NSData(contentsOfFile: path)
. Xem developer.apple.com/library/ios/documentation/Cocoa/Reference/… :
Đưa ra yêu cầu API
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)
Chuẩn bị cho phản ứng
Khai báo một mảng như bên dưới
var data: NSMutableData = NSMutableData()
Nhận được phản hồi
1.
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
// Received a new request, clear out the data object
self.data = NSMutableData()
}
2.
func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
// Append the received chunk of data to our data object
self.data.appendData(data)
}
3.
func connectionDidFinishLoading(connection: NSURLConnection!) {
// Request complete, self.data should now hold the resulting info
// Convert the retrieved data in to an object through JSON deserialization
var err: NSError
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
if jsonResult.count>0 && jsonResult["results"].count>0 {
var results: NSArray = jsonResult["results"] as NSArray
self.tableData = results
self.appsTableView.reloadData()
}
}
Khi NSURLConnection
nhận được phản hồi, chúng tôi có thể mong đợi didReceiveResponse
phương thức được gọi thay mặt chúng tôi. Tại thời điểm này, chúng tôi chỉ cần đặt lại dữ liệu của mình bằng cách nói self.data = NSMutableData()
, tạo một đối tượng dữ liệu trống mới.
Sau khi kết nối được thực hiện, chúng tôi sẽ bắt đầu nhận dữ liệu trong phương thức didReceiveData
. Đối số dữ liệu đang được chuyển vào đây là nơi tất cả thông tin hấp dẫn của chúng ta đến từ. Chúng ta cần giữ từng đoạn dữ liệu đi kèm, vì vậy chúng ta nối nó vào đối tượng self.data mà chúng ta đã xóa trước đó.
Cuối cùng, khi kết nối hoàn tất và tất cả dữ liệu đã được nhận, connectionDidFinishLoading
sẽ được gọi và chúng tôi đã sẵn sàng sử dụng dữ liệu trong ứng dụng của mình. Hoan hô!
Các connectionDidFinishLoading
phương pháp ở đây sử dụng các NSJSONSerialization
lớp để chuyển đổi dữ liệu thô của chúng tôi để có ích Dictionary
đối tượng bằng cách deserializing kết quả từ Url của bạn.
Tôi vừa viết một lớp có tên là JSON, giúp xử lý JSON trong Swift dễ dàng như đối tượng JSON trong ES5.
Chuyển đối tượng nhanh chóng của bạn sang JSON như sau:
let obj:[String:AnyObject] = [
"array": [JSON.null, false, 0, "",[],[:]],
"object":[
"null": JSON.null,
"bool": true,
"int": 42,
"double": 3.141592653589793,
"string": "a α\t弾\n𪚲",
"array": [],
"object": [:]
],
"url":"http://blog.livedoor.com/dankogai/"
]
let json = JSON(obj)
json.toString()
... hoặc chuỗi ...
let json = JSON.parse("{\"array\":[...}")
... hoặc URL.
let json = JSON.fromURL("http://api.dan.co.jp/jsonenv")
Tree Traversal
Chỉ duyệt các phần tử qua chỉ số con:
json["object"]["null"].asNull // NSNull()
// ...
json["object"]["string"].asString // "a α\t弾\n𪚲"
json["array"][0].asNull // NSNull()
json["array"][1].asBool // false
// ...
Cũng giống như SwiftyJSON, bạn không cần lo lắng nếu mục nhập đã đăng ký không tồn tại.
if let b = json["noexistent"][1234567890]["entry"].asBool {
// ....
} else {
let e = json["noexistent"][1234567890]["entry"].asError
println(e)
}
Nếu bạn cảm thấy mệt mỏi với các đăng ký, hãy thêm chương trình của bạn như sau:
//// schema by subclassing
class MyJSON : JSON {
init(_ obj:AnyObject){ super.init(obj) }
init(_ json:JSON) { super.init(json) }
var null :NSNull? { return self["null"].asNull }
var bool :Bool? { return self["bool"].asBool }
var int :Int? { return self["int"].asInt }
var double:Double? { return self["double"].asDouble }
var string:String? { return self["string"].asString }
}
Và bạn đi:
let myjson = MyJSON(obj)
myjson.object.null
myjson.object.bool
myjson.object.int
myjson.object.double
myjson.object.string
// ...
Hy vọng bạn thích nó.
Với xCode 7.3+ mới, điều quan trọng là phải thêm miền của bạn vào danh sách ngoại lệ ( Làm cách nào để thêm NSAppTransportSecurity vào tệp info.plist của tôi? ), Hãy tham khảo bài đăng này để được hướng dẫn, nếu không bạn sẽ gặp lỗi cơ quan truyền tải.
Đây là mã để thực hiện chuyển đổi giữa JSON và NSData trong Swift 2.0
// Convert from NSData to json object
func nsdataToJSON(data: NSData) -> AnyObject? {
do {
return try NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
} catch let myJSONError {
print(myJSONError)
}
return nil
}
// Convert from JSON to nsdata
func jsonToNSData(json: AnyObject) -> NSData?{
do {
return try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions.PrettyPrinted)
} catch let myJSONError {
print(myJSONError)
}
return nil;
}
Trong Swift 4+ được khuyến khích sử dụng Codable
thay vì JSONSerialization
.
Điều này Codable
bao gồm hai giao thức: Decodable
và Encodable
. Decodable
Giao thức này cho phép bạn giải mã Data
ở định dạng JSON thành cấu trúc / lớp tùy chỉnh phù hợp với giao thức này.
Ví dụ, hãy tưởng tượng tình huống mà chúng ta có đơn giản này Data
(mảng gồm hai đối tượng)
let data = Data("""
[
{"name":"Steve","age":56},
{"name":"iPhone","age":11}
]
""".utf8)
sau đó có struct
giao thức theo dõi và triển khaiDecodable
struct Person: Decodable {
let name: String
let age: Int
}
bây giờ bạn có thể giải mã Data
cho mảng của bạn Person
bằng cách sử dụng JSONDecoder
tham số đầu tiên là kiểu tuân theo Decodable
và kiểu này sẽ Data
được giải mã
do {
let people = try JSONDecoder().decode([Person].self, from: data)
} catch { print(error) }
... lưu ý rằng giải mã phải được đánh dấu bằng try
từ khóa vì ví dụ như bạn có thể mắc một số lỗi đặt tên và sau đó mô hình của bạn không thể được giải mã chính xác ... vì vậy bạn nên đặt nó bên trong khối do-try-catch
Các trường hợp khóa trong json khác với tên của thuộc tính:
Nếu khóa được đặt tên bằng cách sử dụng solid_case, bạn có thể đặt bộ giải mã keyDecodingStrategy
để convertFromSnakeCase
thay đổi khóa từ property_name
thành camelCasepropertyName
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
let people = try decoder.decode([Person].self, from: data)
Nếu bạn cần tên duy nhất, bạn có thể sử dụng các khóa mã hóa bên trong struct / class nơi bạn khai báo tên khóa
let data = Data("""
{ "userName":"Codable", "age": 1 }
""".utf8)
struct Person: Decodable {
let name: String
let age: Int
enum CodingKeys: String, CodingKey {
case name = "userName"
case age
}
}
Tôi cũng đã viết một thư viện nhỏ chuyên dùng để ánh xạ phản hồi json thành một cấu trúc đối tượng. Tôi đang sử dụng nội bộ thư viện json-swift từ David Owens. Có thể nó hữu ích cho người khác.
https://github.com/prine/ROJSONParser
Ví dụ Nhân viên.json
{
"employees": [
{
"firstName": "John",
"lastName": "Doe",
"age": 26
},
{
"firstName": "Anna",
"lastName": "Smith",
"age": 30
},
{
"firstName": "Peter",
"lastName": "Jones",
"age": 45
}]
}
Bước tiếp theo, bạn phải tạo mô hình dữ liệu của mình (EmplyoeeContainer và Employee).
Employee.swift
class Employee : ROJSONObject {
required init() {
super.init();
}
required init(jsonData:AnyObject) {
super.init(jsonData: jsonData)
}
var firstname:String {
return Value<String>.get(self, key: "firstName")
}
var lastname:String {
return Value<String>.get(self, key: "lastName")
}
var age:Int {
return Value<Int>.get(self, key: "age")
}
}
EmployeeContainer.swift
class EmployeeContainer : ROJSONObject {
required init() {
super.init();
}
required init(jsonData:AnyObject) {
super.init(jsonData: jsonData)
}
lazy var employees:[Employee] = {
return Value<[Employee]>.getArray(self, key: "employees") as [Employee]
}()
}
Sau đó, để thực sự ánh xạ các đối tượng từ phản hồi JSON, bạn chỉ phải truyền dữ liệu vào lớp EmployeeContainer dưới dạng tham số trong phương thức khởi tạo. Nó tự động tạo mô hình dữ liệu của bạn.
var baseWebservice:BaseWebservice = BaseWebservice();
var urlToJSON = "http://prine.ch/employees.json"
var callbackJSON = {(status:Int, employeeContainer:EmployeeContainer) -> () in
for employee in employeeContainer.employees {
println("Firstname: \(employee.firstname) Lastname: \(employee.lastname) age: \(employee.age)")
}
}
baseWebservice.get(urlToJSON, callback:callbackJSON)
Đầu ra bảng điều khiển sau đó trông giống như sau:
Firstname: John Lastname: Doe age: 26
Firstname: Anna Lastname: Smith age: 30
Firstname: Peter Lastname: Jones age: 45
Đơn giản và dễ đọc!
"mrap"
từ nicknames
dưới dạng Chuỗi từ phản hồi JSON này{
"other": {
"nicknames": ["mrap", "Mikee"]
}
Nó lấy dữ liệu json của bạn NSData
như nó vốn có, không cần phải xử lý trước.
let parser = JSONParser(jsonData)
if let handle = parser.getString("other.nicknames[0]") {
// that's it!
}
Tuyên bố từ chối trách nhiệm: Tôi đã làm điều này và tôi hy vọng nó sẽ giúp ích cho mọi người. Hãy cải thiện nó!
Phân tích cú pháp JSON trong Swift là một công việc tuyệt vời để tạo mã. Tôi đã tạo một công cụ tại http://www.guideluxe.com/JsonToSwift để làm điều đó.
Bạn cung cấp một đối tượng JSON mẫu với tên lớp và công cụ sẽ tạo ra một lớp Swift tương ứng, cũng như bất kỳ lớp Swift phụ cần thiết nào, để đại diện cho cấu trúc được bao hàm bởi JSON mẫu. Cũng bao gồm các phương thức lớp được sử dụng để điền các đối tượng Swift, bao gồm một phương thức sử dụng phương thức NSJSONSerialization.JSONObjectWithData. Các ánh xạ cần thiết từ các đối tượng NSArray và NSDictionary được cung cấp.
Từ mã được tạo, bạn chỉ cần cung cấp một đối tượng NSData chứa JSON phù hợp với mẫu được cung cấp cho công cụ.
Ngoài Foundation, không có phụ thuộc nào.
Công việc của tôi được lấy cảm hứng từ http://json2csharp.com/ , rất tiện dụng cho các dự án .NET.
Đây là cách tạo đối tượng NSData từ tệp JSON.
let fileUrl: NSURL = NSBundle.mainBundle().URLForResource("JsonFile", withExtension: "json")!
let jsonData: NSData = NSData(contentsOfURL: fileUrl)!
Lưu ý: nếu bạn đang tìm kiếm điều này, rất có thể bạn không biết cách cài đặt swifty
. Làm theo hướng dẫn tại đây .
sudo gem install cocoapods
cd ~/Path/To/Folder/Containing/ShowTracker
Tiếp theo nhập lệnh này:
pod init
Điều này sẽ tạo mặc định Podfile
cho dự án của bạn. Đây Podfile
là nơi bạn xác định các phụ thuộc mà dự án của bạn dựa vào.
Nhập lệnh này để mở Podfile
bằng cách sử dụng Xcode
để chỉnh sửa:
open -a Xcode Podfile
Thêm Swifty
vào podfile
platform :ios, '8.0'
use_frameworks!
target 'MyApp' do
pod 'SwiftyJSON', '~> X.X.X'
end
var mURL = NSURL(string: "http://api.openweathermap.org/data/2.5/weather?q=London,uk&units=metric")
if mURL == nil{
println("You are stupid")
return
}
var request = NSURLRequest(URL: mURL!)
NSURLConnection.sendAsynchronousRequest(
request,
queue: NSOperationQueue.mainQueue(),
completionHandler:{ (
response: NSURLResponse!,
data: NSData!,
error: NSError!) -> Void in
if data != nil {
var mJSON = JSON(data: data!)
if let current_conditions = mJSON["weather"][0]["description"].string {
println("Current conditions: " + current_conditions)
} else {
println("MORON!")
}
if let current_temperature = mJSON["main"]["temp"].double {
println("Temperature: "+ String(format:"%.f", current_temperature) + "°C"
} else {
println("MORON!")
}
}
})
Toàn bộ bộ điều khiển chế độ xem hiển thị dữ liệu trong chế độ xem bộ sưu tập bằng cách sử dụng hai phương pháp json parsig
@IBOutlet weak var imagecollectionview: UICollectionView!
lazy var data = NSMutableData()
var dictdata : NSMutableDictionary = NSMutableDictionary()
override func viewDidLoad() {
super.viewDidLoad()
startConnection()
startNewConnection()
// Do any additional setup after loading the view, typically from a nib.
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return dictdata.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CustomcellCollectionViewCell", forIndexPath: indexPath) as! CustomcellCollectionViewCell
cell.name.text = dictdata.valueForKey("Data")?.valueForKey("location") as? String
let url = NSURL(string: (dictdata.valueForKey("Data")?.valueForKey("avatar_url") as? String)! )
LazyImage.showForImageView(cell.image, url:"URL
return cell
}
func collectionView(collectionView: UICollectionView,
layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let kWhateverHeightYouWant = 100
return CGSizeMake(self.view.bounds.size.width/2, CGFloat(kWhateverHeightYouWant))
}
func startNewConnection()
{
let url: URL = URL(string: "YOUR URL" as String)!
let session = URLSession.shared
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "GET" //set the get or post according to your request
// request.cachePolicy = NSURLRequest.CachePolicy.ReloadIgnoringCacheData
request.cachePolicy = NSURLRequest.CachePolicy.reloadIgnoringCacheData
let task = session.dataTask(with: request as URLRequest) {
( data, response, error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
print("error")
return
}
let jsonString = NSString(data: data!, encoding:String.Encoding.utf8.rawValue) as! String
}
task.resume()
}
func startConnection(){
let urlPath: String = "your URL"
let url: NSURL = NSURL(string: urlPath)!
var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)!
connection.start()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
self.data.appendData(data)
}
func buttonAction(sender: UIButton!){
startConnection()
}
func connectionDidFinishLoading(connection: NSURLConnection!) {
do {
let JSON = try NSJSONSerialization.JSONObjectWithData(self.data, options:NSJSONReadingOptions(rawValue: 0))
guard let JSONDictionary :NSDictionary = JSON as? NSDictionary else {
print("Not a Dictionary")
// put in function
return
}
print("JSONDictionary! \(JSONDictionary)")
dictdata.setObject(JSONDictionary, forKey: "Data")
imagecollectionview.reloadData()
}
catch let JSONError as NSError {
print("\(JSONError)")
} }
Sử dụng khung công tác ObjectMapper
if let path = Bundle(for: BPPView.self).path(forResource: jsonFileName, ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: NSData.ReadingOptions.mappedIfSafe)
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
self.levels = Mapper<Level>().mapArray(JSONArray: (json as! [[String : Any]]))!
print(levels.count)
} catch let error as NSError {
print(error.localizedDescription)
}
} else {
print("Invalid filename/path.")
}
Trước khi bạn nên chuẩn bị tập hợp các đối tượng thích hợp: Mappable để phân tích cú pháp
import UIKit
import ObjectMapper
class Level: Mappable {
var levelName = ""
var levelItems = [LevelItem]()
required init?(map: Map) {
}
// Mappable
func mapping(map: Map) {
levelName <- map["levelName"]
levelItems <- map["levelItems"]
}
import UIKit
import ObjectMapper
class LevelItem: Mappable {
var frontBackSide = BPPFrontBack.Undefined
var fullImageName = ""
var fullImageSelectedName = ""
var bodyParts = [BodyPart]()
required init?(map: Map) {
}
// Mappable
func mapping(map: Map) {
frontBackSide <- map["frontBackSide"]
fullImageName <- map["fullImageName"]
fullImageSelectedName <- map["fullImageSelectedName"]
bodyParts <- map["bodyParts"]
}}
Swift 3
let parsedResult: [String: AnyObject]
do {
parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:AnyObject]
} catch {
// Display an error or return or whatever
}
dữ liệu - đó là Kiểu dữ liệu (Cấu trúc) (tức là được trả về bởi một số phản hồi của máy chủ)
Trình phân tích cú pháp này sử dụng generic để truyền các loại JSON sang Swift, điều này làm giảm mã bạn cần nhập.
https://github.com/evgenyneu/JsonSwiftson
struct Person {
let name: String?
let age: Int?
}
let mapper = JsonSwiftson(json: "{ \"name\": \"Peter\", \"age\": 41 }")
let person: Person? = Person(
name: mapper["name"].map(),
age: mapper["age"].map()
)
Dưới đây là một ví dụ về Swift Playground:
import UIKit
let jsonString = "{\"name\": \"John Doe\", \"phone\":123456}"
let data = jsonString.data(using: .utf8)
var jsonObject: Any
do {
jsonObject = try JSONSerialization.jsonObject(with: data!) as Any
if let obj = jsonObject as? NSDictionary {
print(obj["name"])
}
} catch {
print("error")
}
Swift 4
Tạo một dự án
Design StoryBoard với một nút bấm và một UITableview
Tạo TableViewCell VC
Trong hành động nút Chèn mã folloeing
Hãy nhớ mã này để tìm nạp mảng dữ liệu trong Api
import UIKit
class ViewController3: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var displayDatasssss = [displyDataClass]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return displayDatasssss.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell1") as! TableViewCell1
cell.label1.text = displayDatasssss[indexPath.row].email
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func gettt(_ sender: Any) {
let url = "http://jsonplaceholder.typicode.com/users"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request){(data, response,error)in
if (error != nil){
print("Error")
}
else{
do{
// Array of Data
let fetchData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! NSArray
for eachData in fetchData {
let eachdataitem = eachData as! [String : Any]
let name = eachdataitem["name"]as! String
let username = eachdataitem["username"]as! String
let email = eachdataitem["email"]as! String
self.displayDatasssss.append(displyDataClass(name: name, username: username,email : email))
}
self.tableView.reloadData()
}
catch{
print("Error 2")
}
}
}
task.resume()
}
}
class displyDataClass {
var name : String
var username : String
var email : String
init(name : String,username : String,email :String) {
self.name = name
self.username = username
self.email = email
}
}
Điều này dành cho Tìm nạp dữ liệu từ điển
import UIKit
class ViewController3: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet var tableView: UITableView!
var displayDatasssss = [displyDataClass]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return displayDatasssss.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell1") as! TableViewCell1
cell.label1.text = displayDatasssss[indexPath.row].email
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func gettt(_ sender: Any) {
let url = "http://jsonplaceholder.typicode.com/users/1"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request){(data, response,error)in
if (error != nil){
print("Error")
}
else{
do{
//Dictionary data Fetching
let fetchData = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String: AnyObject]
let name = fetchData["name"]as! String
let username = fetchData["username"]as! String
let email = fetchData["email"]as! String
self.displayDatasssss.append(displyDataClass(name: name, username: username,email : email))
self.tableView.reloadData()
}
catch{
print("Error 2")
}
}
}
task.resume()
}
}
class displyDataClass {
var name : String
var username : String
var email : String
init(name : String,username : String,email :String) {
self.name = name
self.username = username
self.email = email
}
}
Tận dụng JSONDecoder().decode
Xem video này phân tích cú pháp JSON với Swift 4
struct Post: Codable {
let userId: Int
let id: Int
let title: String
let body: String
}
URLSession.shared.dataTask(with: URL(string: "https://jsonplaceholder.typicode.com/posts")!) { (data, response, error) in
guard let response = response as? HTTPURLResponse else {
print("HTTPURLResponse error")
return
}
guard 200 ... 299 ~= response.statusCode else {
print("Status Code error \(response.statusCode)")
return
}
guard let data = data else {
print("No Data")
return
}
let posts = try! JSONDecoder().decode([Post].self, from: data)
print(posts)
}.resume()
Swift 2 iOS 9
let miadata = NSData(contentsOfURL: NSURL(string: "https://myWeb....php")!)
do{
let MyData = try NSJSONSerialization.JSONObjectWithData(miadata!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
print(".........\(MyData)")
}
catch let error as NSError{
// error.description
print(error.description)
}