在iOs swift app加载时发出http get请求

时间:2015-10-22 05:51:40

标签: ios iphone json swift http

我在xcode中制作了一个iOs应用,以了解整个开发过程。到目前为止,我已设法从手动硬编码的数组加载数据到tableview。现在我正在尝试从我在其他地方托管的json加载内容。但到现在为止,我没有运气。

截至目前我的代码如下:

import UIKit

class 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:]

2 个答案:

答案 0 :(得分:1)

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()

答案 1 :(得分:1)

只需在!

的末尾添加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 */ })