【发布时间】:2019-03-03 10:27:56
【问题描述】:
我不确定我是否设置正确,但我正在尝试使用 JSON 字符串从服务器接收 iPhone 应用程序上的数据。我为字符串创建了标签,但没有收到数据。我知道服务器正在工作,如果我从命令行运行 curl 我会收到数据。有人可以指出我正确的方向。
ViewController.swift
导入 UIKit
类 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
导入基础 导入 UIKit
protocol TemperatureWebServiceDelegate: class {func temperatureReceived(temperature: String, date: String)}
类 TemperatureWebService: NSObject, URLSessionDelegate {
弱 var 委托: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 导入 UIKit
@UIApplicationMain 类 AppDelegate:UIResponder,UIApplicationDelegate,TemperatureWebServiceDelegate { func temperatureReceived(温度:字符串,日期:字符串){
}
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()的呼叫。另外,不要去掉NSURLConnection,更喜欢URLSession。 -
嗨拉尔姆,谢谢。我在上面的代码中添加了 startConnection()。对吗?