1

Forgive the ignorance in advance; I am stumbling my way through Swift and JSON, and am diligently working to try to deconstruct tutorials and grasp a better understanding.

I have been using the SwiftyJSON example Xcode project (here). If I change the data of the SwiftyJSONTests.json file to include my own desired data, it properly renders when I run the project. My goal is to alter my AppDelegate.swift file to pull data from my live JSON page, rather than the example SwiftyJSONTests.json file.

My AppDelegate.swift file looks like so;

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

I've attempted altering my "let data = "... line to be a "let data = NSURL(contentsOfURL: url)!" and altering "SwiftyJSONTests" to my desired URL, but that's not even remotely close, it seems.

Is there any guidance one could provide to keep the structure of my Storyboard and AppDelegate intact, but have it point to a URL and not the file? I'm interested to learn and dissect.

Thanks so much!

2 Answers 2

3

For a real app, you should always use an asynchronous download method.

Swift 2

NSURLConnection is deprecated, we're using 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()
}

Original Swift 1 version

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)")
    }
})
Sign up to request clarification or add additional context in comments.

Comments

0

Ok, a little example in 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)")

}

in my example I get the data in the array, but you might have them in Dictionary .... good luck

1 Comment

This was a great explanation and provided some awesome reading material for investigation! Thanks so much @RobertoL!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.