Skip to main content
 首页 » 编程设计

ios之将 SwiftyJSON 示例转换为 URL 数据

2024年01月01日79xing901022

恕我无知先行;我在 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 而不是文件?我有兴趣学习和剖析。

非常感谢!

请您参考如下方法:

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

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