【发布时间】:2016-01-21 07:54:18
【问题描述】:
我在 xcode 中制作了一个 iOs 应用程序以了解整个开发过程。到目前为止,我已经设法将数据从手动硬编码的数组加载到 tableview。现在我正在尝试从我在其他地方托管的 json 加载内容。但直到现在我没有运气。
我现在的代码如下:
import UIKit
类 FriendListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
let myFriends = ["Safwan Erooth", "Nadir K", "Salsabeel", "Raheema"]
var selectedFriends = "Safwan"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.tableView.dataSource = self
self.tableView.delegate = self
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.myFriends.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell()
cell.textLabel!.text = myFriends[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.selectedFriends = myFriends[indexPath.row]
self.performSegueWithIdentifier("friendListToFriendDetailSegue", sender: self)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let detailViewController = segue.destinationViewController as! FriendDetailViewController
detailViewController.name = self.selectedFriends
if self.selectedFriends == "Safwan Erooth" {
detailViewController.birthday = "17 Nov"
} else if self.selectedFriends == "Nadir K" {
detailViewController.birthday = "10 Jan"
} else if self.selectedFriends == "Salsabeel" {
detailViewController.birthday = "12 June"
} else if self.selectedFriends == "Raheema" {
detailViewController.birthday = "16 Dec"
}
}
}
我在 [this link][1] 中使用 swift playgroubd 尝试了几个示例。但它不起作用。我在操场上尝试的代码是这样的:
let url = NSURL(string: "http://localhost/test.json")
let request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
print(NSString(data: data, encoding: NSUTF8StringEncoding))
}
我在控制台中收到以下错误。
Oct 22 11:20:22 MyPlayground[1989] <Error>: CGContextSaveGState: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
Oct 22 11:20:22 MyPlayground[1989] <Error>: CGContextTranslateCTM: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
Oct 22 11:20:22 MyPlayground[1989] <Error>: CGContextRestoreGState: invalid context 0x0. If you want to see the backtrace, please set CG_CONTEXT_SHOW_BACKTRACE environmental variable.
Playground execution failed: /var/folders/cg/5wt2_vvx1mg5h73flw26gmvr0000gp/T/./lldb/312/playground6.swift:13:26: error: value of optional type 'NSData?' not unwrapped; did you mean to use '!' or '?'?
print(NSString(data: data, encoding: NSUTF8StringEncoding))
^
实现目标的最佳方式是什么?
更新 1
已添加!根据下面给出的答案在数据末尾签名,但我仍然收到以下错误。
2015-10-22 11:42:26.472 MyPlayground[22151:11326178] Failed to obtain sandbox extension for path=/var/folders/cg/5wt2_vvx1mg5h73flw26gmvr0000gp/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.MyPlayground-42AD40EC-8F3C-470F-B8AE-C9F4AF644932/Library/Caches/com.apple.dt.playground.stub.iOS_Simulator.MyPlayground-42AD40EC-8F3C-470F-B8AE-C9F4AF644932. Errno:1
2015-10-22 11:42:26.472 MyPlayground[22151:11326178] Failed to obtain sandbox extension for path=/var/folders/cg/5wt2_vvx1mg5h73flw26gmvr0000gp/T/com.apple.dt.Xcode.pg/containers/com.apple.dt.playground.stub.iOS_Simulator.MyPlayground-42AD40EC-8F3C-470F-B8AE-C9F4AF644932/Library/Caches/com.apple.dt.playground.stub.iOS_Simulator.MyPlayground-42AD40EC-8F3C-470F-B8AE-C9F4AF644932. Errno:1\
更新 2
尝试了以下代码:
let components = NSURLComponents()
components.scheme = "http"
components.host = "localhost"
components.path = "/test.json"
let sessionURL = components.URL!
let request = NSURLRequest(URL: sessionURL)
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request) {
(data, response, error) -> Void in
if error == nil{
//then save json to a variable/constant
//this casts the son to an array of dictionaries
yourJSON = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as! [NSDictionary]
}
}
task.resume()
但出现错误error: use of unresolved identifier 'yourJSON'
也试过下面的代码:
let url = NSURL(string: "http://httpbin.org/get")
let request:NSURLRequest = NSURLRequest(URL:url)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ response, data, error in /* Your code */ })
但得到了错误:
error: value of optional type 'NSURL?' not unwrapped; did you mean to use '!' or '?'?
和
warning: 'sendAsynchronousRequest(_:queue:completionHandler:)' was deprecated in iOS 9.0: Use [NSURLSession dataTaskWithRequest:completionHandler:]
【问题讨论】:
-
检查浏览器中的URL,URL是否包含数据然后尝试你的代码,我在浏览器中检查了你的URL,浏览器说它的URL无效,试试有效的URL你肯定会得到答案
-
网址在我的本地主机中。
标签: ios iphone json swift http