duanji9481 2016-09-30 19:49
浏览 53
已采纳

PHP,Xcode 8,Swift 3 - 如何将数组从Web服务器返回到Xcode模拟器

I can read text from a web server and print it to the Xcode uilabel, but I don't know how to parse a returning array. I am trying to get a and b from the server, add them, and print to uilabel using Swift 3.

This is the PHP and Xcode 8:

connect-add.php

<?php
$a=3;
$b=5;
$data=array($a,$b);
echo json_encode($data);
?>

Xcode 8

import UIKit
import Foundation

class ViewController: UIViewController {

var a=0
var b=0
var c=0


@IBOutlet weak var result: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a 
nib.
}

@IBAction func getVars(_ sender: AnyObject) {

    // set label during request

    self.result.text="WAITING"

    // send request to connect-add.php and retrieve a and b

    let myUrl = NSURL(string: "http://www.example.com/connect-add.php")

    var request = URLRequest(url:URL(string: 
"http://www.example.com/connect-add.php")!)

    request.httpMethod = "POST"

    let postString = ""

    request.httpBody = postString.data(using: .utf8);

    let task = URLSession.shared.dataTask(with: request) {
        data, response, error in

        if error != nil
        {
            print("error=\(error)")
            return
        }

        // receive response to connect-add and parse to a and b

        var response = String(data: data!, encoding: .utf8)

        var a=response[0]
        var b=response[1]

        // add a and b and display

        var c=a+b
        self.result.text=c
    }
    task.resume()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

Xcode gives me an error for setting var a=response[0] and for setting var b=response[1]. Any ideas?

I have editted PHP and Xcode to add JSON Serialization parsing. Xcode is showing one error--Use of unresolved identifier "JSON". Here is the code.

PHP

<?php
$a=3;
$b=5;
$data="a1=".$a.", b1=".$b;
echo json_encode($data);
?>

Xcode 8

import UIKit
import Foundation

class ViewController: UIViewController {

var a=0
var b=0
var c=0


@IBOutlet weak var result: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a 
nib.
}

@IBAction func getVars(_ sender: AnyObject) {

    // set label during request

    self.result.text="WAITING"

    // send request to connect-add.php and retrieve a and b

    let myUrl = NSURL(string: "http://www.example.com/connect-add.php")

    var request = URLRequest(url:URL(string: 
"http://www.example.com/connect-add.php")!)

    request.httpMethod = "POST"

    let postString = ""

    request.httpBody = postString.data(using: .utf8);

    let task = URLSession.shared.dataTask(with: request) {
        data, response, error in

        if error != nil
        {
            print("error=\(error)")
            return
        }

        // receive response to connect and parse to a and b

        var response = String(data: data!, encoding: .utf8)

        var obj=JSON.parse(response)

        var a=obj.a1
        var b=obj.b1

        // add a and b and display

        var c=a+b
        self.result.text=c
    }
    task.resume()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}
  • 写回答

1条回答 默认 最新

  • dongqian3750 2016-11-04 18:18
    关注
    if var json = try JSONSerialization.jsonObject(with: data) as? [String: 
    String], var a2 = json["a"], var b2 = json["b"] {
    // It's working
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 已有python代码,要求做成可执行程序,程序设计内容不多
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥15 小红薯封设备能解决的来
  • ¥100 求采集电商背景音乐的方法
  • ¥15 数学建模竞赛求指导帮助
  • ¥15 STM32控制MAX7219问题求解答
  • ¥20 在本地部署CHATRWKV时遇到了AttributeError: 'str' object has no attribute 'requires_grad'
  • ¥15 vue+element项目中多tag时,切换Tab时iframe套第三方html页面需要实现不刷新
  • ¥50 深度强化学习解决能源调度问题