简体   繁体   English

当iOs快速应用加载时发出http获取请求

[英]Make http get request when iOs swift app loads

I making an iOs app in xcode to understand the whole development process. 我用xcode制作了一个iOs应用程序,以了解整个开发过程。 So far I have managed to load data to tableview from an array manually hard coded. 到目前为止,我已经设法将数据从手动硬编码的数组加载到tableview中。 Now I am trying to load content from a json I have hosted elsewhere. 现在,我试图从其他地方托管的json加载内容。 But till now I had no luck with the same. 但是直到现在我都没有运气。

My code as of now is below: 到目前为止,我的代码如下:

import UIKit

class FriendListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { 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"

    }

  }

 }

I tried few examples in [this link][1] using the swift playgroubd. 我使用swift playgroubd在[this link] [1]中尝试了一些示例。 But its not working. 但是它不起作用。 The code i am trying in playground is this: 我在操场上尝试的代码是这样的:

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

I get the following error in console. 我在控制台中收到以下错误。

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

What would be the best way to achieve what am trying to do? 实现目标的最佳方法是什么?

Update 1 更新1

Added ! 添加 ! sign at the end of data as per answer given below, but i still get the below error. 根据以下给出的答案在数据末尾签名,但我仍然收到以下错误。

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\

Update 2 更新2

Tried the below code: 尝试了以下代码:

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

But got an error error: use of unresolved identifier 'yourJSON' 但是出现一个错误error: use of unresolved identifier 'yourJSON'

Also tried below code: 还尝试了以下代码:

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 */ })

But got the error: 但是得到了错误:

error: value of optional type 'NSURL?' not unwrapped; did you mean to use '!' or '?'?

And

warning: 'sendAsynchronousRequest(_:queue:completionHandler:)' was deprecated in iOS 9.0: Use [NSURLSession dataTaskWithRequest:completionHandler:]

Apple has deprecated the NSURLConnection methods and you should now use NSURLSession instead. Apple已弃用NSURLConnection方法,现在应改为使用NSURLSession。

Try This 尝试这个

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

Just add ! 只需添加! sign at the end of data : data末尾签名:

print(NSString(data: data!, encoding: NSUTF8StringEncoding))

and it will work ;) 它会工作;)

UPDATE 更新

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM