使用 Swift 2 和 PHP 将 JSON 编码为 Xcode 7
Encode JSON to Xcode 7 with Swift 2 and PHP
我在 let task = session 行出错,应用程序运行但是当 json 尝试加载应用程序时停止并在控制台中显示致命错误:
unexpectedly found nil while unwrapping an Optional value
我只是想显示我服务器上的 JSON,当我更新到 Xcode 7
时,这个问题就开始了
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let jsonUrl = "{http://test.yozzibeens.com/AppTesting/JsonArray.php}"
let session = NSURLSession.sharedSession()
let shotsUrl = NSURL(string: jsonUrl)
let task = session.dataTaskWithURL(shotsUrl!)
{
(data, response, error) -> Void in
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
print(String(jsonData["ip"]!))
} catch _ {
// Error
}
}
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
您需要转义花括号:
let jsonUrl = "{http://test.yozzibeens.com/AppTesting/JsonArray.php}"
let escapeJSONURL = jsonUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let shotsUrl = NSURL(string: escapeJSONURL)
我在 let task = session 行出错,应用程序运行但是当 json 尝试加载应用程序时停止并在控制台中显示致命错误:
unexpectedly found nil while unwrapping an Optional value
我只是想显示我服务器上的 JSON,当我更新到 Xcode 7
时,这个问题就开始了class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let jsonUrl = "{http://test.yozzibeens.com/AppTesting/JsonArray.php}"
let session = NSURLSession.sharedSession()
let shotsUrl = NSURL(string: jsonUrl)
let task = session.dataTaskWithURL(shotsUrl!)
{
(data, response, error) -> Void in
do {
let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSDictionary
print(String(jsonData["ip"]!))
} catch _ {
// Error
}
}
task.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
您需要转义花括号:
let jsonUrl = "{http://test.yozzibeens.com/AppTesting/JsonArray.php}"
let escapeJSONURL = jsonUrl.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let shotsUrl = NSURL(string: escapeJSONURL)