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:.
}
}
startConnection()
. Also, don't get rid ofNSURLConnection
, prefersURLSession
. – Larme