【问题标题】:Converting SwiftyJSON Example to URL Data将 SwiftyJSON 示例转换为 URL 数据
【发布时间】:2016-03-05 00:19:29
【问题描述】:

提前原谅无知;我在 Swift 和 JSON 中磕磕绊绊,并且正在努力尝试解构教程并更好地理解。

我一直在使用 SwiftyJSON 示例 Xcode 项目(此处)。如果我更改 SwiftyJSONTests.json 文件的数据以包含我自己想要的数据,它会在我运行项目时正确呈现。我的目标是更改我的 AppDelegate.swift 文件以从我的实时 JSON 页面中提取数据,而不是示例 SwiftyJSONTests.json 文件。

我的 AppDelegate.swift 文件看起来像这样;

import UIKit
import SwiftyJSON

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    let navigationController = self.window?.rootViewController as! UINavigationController
    let viewController = navigationController.topViewController as! ViewController

    if let file = NSBundle(forClass:AppDelegate.self).pathForResource("SwiftyJSONTests", ofType: "json") {
        let data = NSData(contentsOfFile: file)!
        let json = JSON(data:data)
        viewController.json = json
    } else {
        viewController.json = JSON.nullJSON
    }

    return true
    }
}

我尝试将我的“let data =”... 行更改为“let data = NSURL(contentsOfURL: url)!”并将“SwiftyJSONTests”更改为我想要的 URL,但这似乎还不是很接近。

是否可以提供任何指导来保持我的 Storyboard 和 AppDelegate 的结构完整,但让它指向 URL 而不是文件?我有兴趣学习和剖析。

非常感谢!

【问题讨论】:

    标签: ios json swift


    【解决方案1】:

    对于真正的应用程序,您应该始终使用异步下载方法。

    斯威夫特 2

    NSURLConnection 已弃用,我们正在使用 NSURLSession。

    if let url = NSURL(string: "http://myurl.com/myfile.json") {
        NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: { (data, response, error) in
            if let error = error {
                print("Error: \(error.localizedDescription)")
            } else {
                if let data = data {
                    let json = JSON(data: data)
                    print(json)
                } else {
                    print("no data")
                }
            }
        }).resume()
    }
    

    原始 Swift 1 版本

    let url = NSURL(string: "http://myurl.com/myfile.json")
    let request = NSURLRequest(URL: url!)
    NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!, data: NSData!, error: NSError!) -> Void in
        if error == nil {
            let json = JSON(data: data!)
            println(json)
        }
        else {
            println("Error: \(error.localizedDescription)")
        }
    })
    

    【讨论】:

      【解决方案2】:

      好的,Swift 1.2 Xcode 6.3 中的一个小例子

      class ViewController: UIViewController  {
      
      var data :NSMutableData = NSMutableData()
       URLJson()
      
      }
      
      func URLJson(){
      
          data = NSMutableData()
          let urlPath: String = "http://www.myUrl........"
      
          var url: NSURL = NSURL(string: urlPath)!
          var request: NSURLRequest = NSURLRequest(URL: url)
          var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
          connection.start()
      
      }
      
      func connection(connection: NSURLConnection!, didReceiveData data: NSData!){
      
          self.data.appendData(data)
      
      }
      
      func connectionDidFinishLoading(connection: NSURLConnection!)
      
      {
          var error: NSErrorPointer=nil
      
          var jsonResult: NSArray = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: error) as! NSArray
      
          //print json Result
          println(jsonResult)
      
          var  title :NSArray =  jsonResult.valueForKey("title") as! NSArray
          var text  :NSArray = jsonResult.valueForKey("introtext")as! NSArray
      
      
      
      
          println("title \(title)")
      

      }

      在我的示例中,我在数组中获取数据,但您可能在字典中拥有它们......祝你好运

      【讨论】:

      • 这是一个很好的解释,并为调查提供了一些很棒的阅读材料!非常感谢@RobertoL!
      猜你喜欢
      • 1970-01-01
      • 2016-03-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-13
      相关资源
      最近更新 更多