事先原谅无知;我正在通过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而不是文件?我有兴趣学习和剖析。
非常感谢!
答案 0 :(得分:3)
对于真实应用,您应该始终使用异步下载方法。
Swift 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)")
}
})
答案 1 :(得分:0)
好的,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)")
}
在我的示例中,我获取了数组中的数据,但您可能在Dictionary中使用它们......祝你好运