Xcode JSON字符串以接收数据

时间:2018-09-27 13:26:19

标签: ios json string xcode

我不确定Im是否正确设置,但我正在尝试使用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

协议TemperatureWebServiceDelegate:类{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:.
}

}

1 个答案:

答案 0 :(得分:0)

跑步时

let webService = TemperatureWebService()

您正在创建一个局部变量,该变量在执行此功能(viewWillAppear)时仍然存在。 viewWillAppear完成后,它将删除对此变量的本地引用,这意味着不再有对其的强引用,这意味着它将被释放。这就是为什么永远不会调用您的委托呼叫并且您没有获取数据的原因。相反,如果您在类ViewController中创建局部变量,例如:

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

为标签制作网点的位置。当您的ViewController类保存在内存中时,它将强烈引用您的TemperatureWebService类。然后,您也可以一起删除viewWillAppear函数。您还缺少对startConnection()的函数调用,就像提到的larme一样。

另一件事值得一提:

var delegate: TemperatureWebServiceDelegate?

将导致TemperatureWebService对其引用保持强烈引用。我们应该将此属性标记为弱,否则我们将在这里保留一个周期,其中ViewController-> TemperatureWebService-> ViewController,因此即使我们尝试也永远不会取消分配它们清理ViewController

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