[英]Make http get request when iOs swift app loads
我用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"
}
}
}
我使用swift playgroubd在[this link] [1]中嘗試了一些示例。 但是它不起作用。 我在操場上嘗試的代碼是這樣的:
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:]
Apple已棄用NSURLConnection方法,現在應改為使用NSURLSession。
嘗試這個
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
let <#yourJSON#> = try! NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as! [NSDictionary]
}
}
task.resume()
只需添加!
在data
末尾簽名:
print(NSString(data: data!, encoding: NSUTF8StringEncoding))
它會工作;)
更新
let url:NSURL = NSURL(string: "your_url_here")
let request:NSURLRequest = NSURLRequest(URL:url)
let queue:NSOperationQueue = NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ response, data, error in /* Your code */ })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.