【问题标题】:http request with consumer key in swift 3.0swift 3.0中带有消费者密钥的http请求
【发布时间】:2017-08-16 19:05:07
【问题描述】:

我对 Swift 很陌生,我正在尝试使用使用者密钥和使用者秘密向 URL 发出 http 请求,老实说,我不确定这在 Swift 中是否可行。

我一直在尝试使用身份验证方法进行这项工作,但它只会给我一个错误。

我的代码(希望这可以帮助您理解我正在尝试做的事情..)

let baseUrl = "my url"
let consumer_key = "consumer_key"
let consumer_secret = "consumer_secret"

let loginString = NSString(format:"%@:%@", consumer_key, consumer_secret)
let loginData = loginString.data(using: String.Encoding.utf8.rawValue)!
let base64LoginString = loginData.base64EncodedString()

let url = URL(string: baseUrl)
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

let config = URLSessionConfiguration.default
let authString = "Basic \(base64LoginString)"
config.httpAdditionalHeaders = ["Authorization" : authString]
let session = URLSession(configuration: config)

 session.dataTask(with: url!) {
     (data, response, error) in
     if (response as? HTTPURLResponse) != nil {
        print("in session")
        let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        print("data please...",dataString!)
      }
  }.resume()

如果这个带有消费者密钥和消费者秘密的 http 调用在 Swift 中是完全不可接受的,或者如果我有任何其他方法可以通过这个,请告诉我。

先谢谢你了。

编辑------------------------------ --------

import UIKit


class OrdersViewController: UIViewController {


    @IBOutlet weak var orderView: UITableView!

    var orderData = [[String: AnyObject]]()
    var selectedIndex = -1

    override func viewDidLoad() {
        super.viewDidLoad()
        print("in")
        // Do any additional setup after loading the view.
        let baseUrl = "my url"
        let consumer_key = "consumer_key"
        let consumer_secret = "consumer_secret"

        let loginString = NSString(format:"%@:%@", consumer_key, consumer_secret)
        let loginData = loginString.data(using: String.Encoding.utf8.rawValue)!
        let base64LoginString = loginData.base64EncodedString()

        let url = URL(string: baseUrl)
        var request = URLRequest(url: url!)
        request.httpMethod = "GET"
        request.setValue("Basic \(base64LoginString)", forHTTPHeaderField: "Authorization")

        let config = URLSessionConfiguration.default
        let authString = "Basic \(base64LoginString)"
        config.httpAdditionalHeaders = ["Authorization" : authString]
        let session = URLSession(configuration: config)

        session.dataTask(with: url!) {
            (data, response, error) in
            if (response as? HTTPURLResponse) != nil {
                print("in session")
                let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
                print("data please...",dataString!)
            }
        }.resume()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return orderData.count
    }

    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if (selectedIndex == indexPath.row) {
            return 100
        } else {
            return 40
        }
    }

    func tableView(tableView: UITableView, cellforRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cellIdentifier = "Cell"
        let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier) as! orderCell

        let obj = orderData[indexPath.row]
        print("obj", obj)

        return cell
    }

}

【问题讨论】:

  • 就代码而言,您的代码看起来不错。身份验证机制本身可能取决于您正在访问的服务器。但是您是否看到任何错误,或者您只是想验证您的代码是否遵循可接受的编码准则?
  • 我不认为它不会运行 session.dataTask 因为我在我的窗口中没有看到我的“会话中”和“请数据...”。我看到一些错误,例如“无法识别的选择器发送到实例 0x7fecb1800490”和“应用程序传输安全已阻止明文 HTTP (http://) 资源加载,因为它不安全。可以通过应用程序的 Info.plist 文件配置临时异常。”最后“以 NSException 类型的未捕获异常终止”

标签: swift api http authentication


【解决方案1】:

根据您的回复,您似乎遇到了 ATS 问题 - 网络代码根本没有运行,因为 URL 是 http:// URL 而不是 https:// 。

如果您有一个带有 https:// 的安全 URL,我建议您使用它。否则,您可以添加 ATS 异常,如以下 SO 线程中所述: Transport security has blocked a cleartext HTTP

【讨论】:

  • 感谢您的评论。但尽管我在我的 plist 中添加了 ATS,但它仍然不起作用。我什至尝试使用 https:// 作为域,但结果相同。
  • 添加ATS后出现什么错误?如果正确添加了 ATS(根据我链接到的 SO 线程),您应该不会看到“App Transport Security 已阻止明文 HTTP”错误消息。如果您仍然看到该消息,则可能未正确设置 ATS 异常。
  • 我没有看到诸如“应用程序传输安全性阻止明文 HTTP”之类的错误,但我看到了诸如“无法识别的选择器发送到实例 0x7fbc5840b050”、“由于未捕获的异常 'NSInvalidArgumentException 而终止应用程序”之类的错误', reason: '" 最后显示了一些 First throw 调用堆栈和“libc++abi.dylib:以 NSException 类型的未捕获异常终止”。所以我猜我的域很好,但是我使用 NS 语法的方式是错误的?
  • 抱歉,编辑我的错误,其中一个错误说,“由于未捕获的异常 'NSInvalidArgumentException' 而终止应用程序,原因:'-[ViewController tableView:numberOfRowsInSection:]: unrecognized selector sent to instance 0x7fc35f401810' . 希望这能帮助你更好地理解。谢谢。
  • 你能把numberOfRowsInSection方法的内容贴出来吗?也许看看代码可能会帮助我告诉你发生了什么。否则,我可能需要实际运行代码以查看问题所在...
【解决方案2】:

我通过更改我的 URLsession 函数解决了这个问题。

session.dataTask(with: url!, completionHandler: {
        (data, response, error) in
            if (error != nil) {
                print("in session error", error.debugDescription)
            } else {
                do {
                    print("in session")
                    self.orderData = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
                    OperationQueue.main.addOperation {
                        self.orderView.reloadData()
                        print("data", self.orderData)
                    }
                } catch let error as NSError {
                    print(error)
                }
            }
        }).resume()

现在我在控制台中看到“会话中”,这意味着它可以正确地进行 http 调用,但我遇到了一个新问题,上面写着 Cannot assign value of type 'NSDictionary' to type '[[String: AnyObect]]'。但我仍然很高兴我的 http 调用有效,最后我可以开始解决另一个问题。 谢谢大家的帮助,我希望这个答案也可以帮助其他人。

【讨论】:

    猜你喜欢
    • 2015-09-25
    • 1970-01-01
    • 1970-01-01
    • 2015-10-26
    • 2012-07-29
    • 2016-04-14
    • 2013-07-04
    • 2014-08-23
    • 1970-01-01
    相关资源
    最近更新 更多