我正在尝试使用swift获取请求并填充我的i<=N
。截至目前,我已准备好table view
数据,需要在我的json
中填写
由于我刚开始学习swift,我发现提出请求有点令人困惑。这是我的table
RestaurantTableViewController.swift
这是我迄今为止所做的一切,在此之后,我应该如何让override func viewDidLoad() {
super.viewDidLoad()
var url: String = "http://localhost:8888/restaurant/registeruser.php"
var request: NSMutableURLRequest = NSMutableURLRequest()
request.URL = NSURL(string: url)
request.HTTPMethod = "GET"
request.timeoutInterval = 60
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) { (respose:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
var error: AutoreleasingUnsafeMutablePointer<NSError?> = nil
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
if (jsonResult != nil){
//success
println(jsonResult)
let dataArray = jsonResult["name"] as! NSArray;
for item in dataArray { //loop through data items
let obj = item as! NSDictionary
for(key, value) in obj{
let allnames = obj["name"] as! NSString;
}
}
}
}
}
充满table
,restaurant name
和type
。任何彻底的帮助将不胜感激。
答案 0 :(得分:1)
我建议使用https://github.com/daltoniam/JSONJoy-Swift它会使事情变得更容易和更清洁。
至于电话
var DISPATCH_TIME_FOREVER: UInt64 { get }
var url: String = "http://localhost:8888/restaurant/registeruser.php"
let sem = dispatch_semaphore_create(0)
var responseData = NSData()
NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {(data, response, error) -> Void in
responseData = data
dispatch_semaphore_signal(sem)
}).resume()
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER)
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers, error: error) as? NSDictionary
if (jsonResult != nil){
//success
println(jsonResult)
let dataArray = jsonResult["name"] as! NSArray;
for item in dataArray { //loop through data items
let obj = item as! NSDictionary
for(key, value) in obj{
let allnames = obj["name"] as! NSString;
}
}
}
答案 1 :(得分:0)
最好的代码如下我每次做请求都用它希望对你有帮助!
let url = URL(string: "https://google.com")
let task = URLSession.shared.dataTask(with: ((url ?? URL(string: "https://google.com"))!)) { [self] (data, response, error) in
do {
let jsonResponse = try JSONSerialization.jsonObject(with: data!, options: [])
print(jsonResponse)
guard let newValue = jsonResponse as? [String:Any] else {
print("invalid format")
}
}
catch let error {
print("Error: \(error)")
}
task.resume()
}