1
votes

Im not sure if Im setting it up right, but I'm trying to receive data on an iPhone app from a server using a JSON string. I have created labels for the string but I don't receive the data. I know the server is working and if I run curl from command line I receive the data. Could someone point me in the right direction.

ViewController.swift

import UIKit

class TemperatureWebServer: UIViewController, TemperatureWebServiceDelegate {

@IBOutlet var currentTempLabel: UILabel!
@IBOutlet var lastUpdatedLabel: UILabel!

private var webService = TemperatureWebService()

override func viewDidLoad() {
    super.viewDidLoad()
    webService.delegate = self
    webService.startConnection()
}

func temperatureReceived(temperature: String, date: String)
{
    currentTempLabel.text = "\(temperature) °C"
    lastUpdatedLabel.text = "\(date)"
}

}

TemperatureWebServer.swift

import Foundation import UIKit

protocol TemperatureWebServiceDelegate: class {func temperatureReceived(temperature: String, date: String)}

class TemperatureWebService: NSObject, URLSessionDelegate {

weak var delegate: TemperatureWebServiceDelegate?

var data = NSMutableData()
var jsonResult: NSArray = []

func startConnection()
{
    let url = URL(string: "http://192.168.0.10/tempjson.php")!
    let request = URLRequest(url:url,cachePolicy:.reloadIgnoringLocalCacheData,timeoutInterval: 60.0)
    URLSession.shared.dataTask(with:request)
    {
        (data,response,error) in
        if (error as NSError?) != nil
        {
            return
        }
        let response = response as! HTTPURLResponse;

        guard (200...299).contains(response.statusCode)

            else
        {
            return
        }
        _ = data!
        }
        .resume()


}

private func connection(connection: URLSessionConfiguration!, didReceiveData data: NSData!)
{
    self.data.append(data as Data)
}

func connectionDidFinishLoading(connection: URLSession!)
{

    getLatestTempReading();
}

func getLatestTempReading()
{
    let dictionary: NSDictionary = jsonResult.lastObject as! NSDictionary
    let tempValue = dictionary.object(forKey: "Temp") as! String
    let dateValue = dictionary.object(forKey: "Date") as! String


    if (delegate != nil)
    {
        if (delegate != nil)
        {
            delegate?.temperatureReceived(temperature: tempValue, date: dateValue)
        }
    }
}

}

AppDelegate import UIKit

@UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, TemperatureWebServiceDelegate { func temperatureReceived(temperature: String, date: String) {

}


var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    return true
}

func applicationWillResignActive(_ application: UIApplication) {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

}

1
I see no call to startConnection(). Also, don't get rid of NSURLConnection, prefers URLSession.Larme
Hi Larme, thanks. I added startConnection() to the code above. Is this right?00BEAR

1 Answers

0
votes

When you run

let webService = TemperatureWebService()

you're making a local variable that lives while this function (viewWillAppear) is being executed. Once viewWillAppear finishes, it will remove the local reference to this variable, which will mean there are no more strong references to it, which means it'll be deallocated. That's why your delegate call is never called and you're not getting your data. Instead, if you make a local variable inside your class ViewController like:

class ViewController: UIViewController, TemperatureWebServiceDelegate {

    @IBOutlet var currentTempLabel: UILabel!
    @IBOutlet var lastUpdatedLabel: UILabel!
    private var webService = TemperatureWebService()

    override func viewDidLoad() {
        super.viewDidLoad()
        webService.delegate = self
        webService.startConnection()
    }

where you made your outlets for your labels. While your ViewController class lives in memory, it'll keep a strong reference to your TemperatureWebService class. Then you could remove your viewWillAppear function all together as well. You're also missing a function call to startConnection() like larme mentioned.

Another thing worth mentioning:

var delegate: TemperatureWebServiceDelegate?

will cause TemperatureWebService to keep a strong reference to its delegate. We should mark this property with weak or else we'll have a retain cycle here, where ViewController -> TemperatureWebService -> ViewController, so they'll never be deallocated even if we try to clean up ViewController

weak var delegate: TemperatureWebServiceDelegate? // to make sure we don't make retain cycles