【问题标题】:Make http get request when iOs swift app loads当 iOs swift 应用程序加载时发出 http get 请求
【发布时间】: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


【解决方案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()

【讨论】:

  • 我仍然收到错误,我已经更新了问题。请检查。
  • 我收到此错误error: use of unresolved identifier 'yourJSON'
  • 把 let 放在你的 JSON 之前,让你的 JSON
  • 你为什么要让它变得比需要的更困难?我告诉过你 NSURLconnection 已被弃用,这就是我给你 NSURLSession 代码的原因。错误:使用未解析的标识符“yourJSON”是因为 yourJSON 是您将自己的名称添加到变量/常量的线索,因为它更适合您的代码使用。我已经编辑了代码,因此您可以复制粘贴,因为无论如何您都可以这样做。
  • 很抱歉考验您的耐心。这是我第一次尝试同时使用 Swift 语言和 Xcode。对于那个很抱歉。我真的很感激你抽出的时间。仅在 php 和 js 方面有经验,Swift 非常具有挑战性,但学习起来很有趣。我也接受了你的回答。也许您可以考虑取消反对票。
【解决方案2】:

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

【讨论】:

  • @RyanTCB 这就是控制台日志所说的
  • 是的,我也说过:)
  • @esafwan 你能把你的网址改成:let url = NSURL(string: "http://httpbin.org/get")吗?由于您的本地主机,可能是您的错误
  • @OrkhanAlizade 对不起,我现在正在检查。我出去工作了。谢谢
  • @OrkhanAlizade 没用。我收到 2 条错误消息。错误 1:error: value of optional type 'NSURL?' not unwrapped; did you mean to use '!' or '?'? 错误二:`警告:'sendAsynchronousRequest(_:queue:completionHandler:)' 在 iOS 9.0 中已弃用:使用 [NSURLSession dataTaskWithRequest:completionHandler:]`
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-15
  • 1970-01-01
  • 2023-03-28
  • 2019-11-30
  • 2017-05-29
  • 1970-01-01
相关资源
最近更新 更多