对php的Swift 4 Json请求
我需要你的帮助。 我试图用Xcode Swift4编写json请求 对PHP的Json请求:对php的Swift 4 Json请求,php,json,swift,request,swift4,Php,Json,Swift,Request,Swift4,我需要你的帮助。 我试图用Xcode Swift4编写json请求 对PHP的Json请求: var request = URLRequest(url: URL(string: "http://example.net/stock_service3.php")!) request.httpMethod = "POST" let postString = "id=112m&name=123" request.httpBody = postStr
var request = URLRequest(url: URL(string: "http://example.net/stock_service3.php")!)
request.httpMethod = "POST"
let postString = "id=112m&name=123"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
}
task.resume()
这是在我的web服务器中包含mySQL PHP代码的示例:
<?php
// Create connection
$con=mysqli_connect("example.mysql:3306","example.net","3445432FruRjCAFk","example.net");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$postdata = json_decode(file_get_contents("php://input"),TRUE);
$id= $postdata["id"];
$name = $postdata["name"];
// Store values in an array
$returnValue = array($id,$name);
// Send back request in JSON format
echo json_encode($returnValue);
// Select all of our stocks from table 'stock_tracker'
$sql ="SELECT m.*
, ( ACOS( COS( RADIANS( $id) )
* COS( RADIANS( m.latitude ) )
* COS( RADIANS( m.longitude ) - RADIANS( $name) )
+ SIN( RADIANS($id) )
* SIN( RADIANS( m.Latitude) )
)
* 6371
) AS distance_in_km
FROM TankBilliger m
HAVING distance_in_km <= 100
ORDER BY distance_in_km ASC
LIMIT 100";
// Confirm there are results
if ($result = mysqli_query($con, $sql))
{
// We have results, create an array to hold the results
// and an array to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each result
while($row = $result->fetch_object())
{
// Add each result into the results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
我的mysql代码可以工作,但如果我想使用从Swift获得的变量更改查询,Swift告诉我:[10788:3159246]无法将类型为“NSNull”(0x108589850)的值强制转换为“NSDictionary”(0x108589288)
我希望查询得到swift的号码
这是我的应用程序向我的iOS应用程序显示mysql数据的代码,这是出现错误的代码
import Foundation
protocol FeedmodelProtocol: class {
func itemsDownloaded(items: NSArray)
}
class Feedmodel: NSObject, URLSessionDataDelegate {
weak var delegate: FeedmodelProtocol!
let urlPath = "http://example.net/stock_service3.php" //Change to the web address of your stock_service.php file
func downloadItems() {
let url: URL = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Error")
}else {
print("stocks downloaded")
self.parseJSON(data!)
}
}
task.resume()
}
func parseJSON(_ data:Data) {
var jsonResult = NSArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
} catch let error as NSError {
print(error)
}
var jsonElement = NSDictionary()
let stocks = NSMutableArray()
for i in 0 ..< jsonResult.count
{
jsonElement = jsonResult[i] as! NSDictionary
let stock = Stockmodel()
//the following insures none of the JsonElement values are nil through optional binding
if let Datum = jsonElement["Datum"] as? String,
let Tankstelle = jsonElement["Tankstelle"] as? String,
let Kraftstoff1 = jsonElement["Kraftstoff1"] as? String,
let Preis1 = jsonElement["Preis1"] as? String,
let Kraftstoff2 = jsonElement["Kraftstoff2"] as? String,
let Preis2 = jsonElement["Preis2"] as? String,
let Notiz = jsonElement["Notiz"] as? String,
let longitude = jsonElement["longitude"] as? String,
let latitude = jsonElement["latitude"] as? String
{
print (Datum)
print(Tankstelle)
print(Kraftstoff1)
print(Preis1)
print(Kraftstoff2)
print(Preis2)
print(Notiz)
print(longitude)
print(latitude)
stock.Datum = Datum
stock.Tankstelle = Tankstelle
stock.Kraftstoff1 = Kraftstoff1
stock.Preis1 = Preis1
stock.Kraftstoff2 = Kraftstoff2
stock.Preis2 = Preis2
stock.Notiz = Notiz
stock.longitude = longitude
stock.latitude = latitude
}
stocks.add(stock)
}
DispatchQueue.main.async(execute: { () -> Void in
self.delegate.itemsDownloaded(items: stocks)
})
}
}
<代码>导入基础
协议FeedmodelProtocol:class{
func项目下载(项目:NSArray)
}
类Feedmodel:NSObject,URLSessionDataDelegate{
弱var委托:FeedmodelProtocol!
让urlPath=”http://example.net/stock_service3.php“//更改stock_service.php文件的网址
func下载项目(){
让url:url=url(字符串:urlPath)!
让DeFultStase= Fuff.UnLeScript(配置:URLSeSealStutial.Debug)
让task=defaultSession.dataTask(带:url){(数据、响应、错误)在
如果错误!=nil{
打印(“错误”)
}否则{
打印(“股票下载”)
self.parseJSON(数据!)
}
}
task.resume()
}
func parseJSON(data:data){
var jsonResult=NSArray()
做{
jsonResult=尝试将JSONSerialization.jsonObject(使用:data,options:JSONSerialization.ReadingOptions.allowFragments)作为!NSArray
}将let错误捕获为NSError{
打印(错误)
}
var jsonElement=NSDictionary()
让stocks=NSMutableArray()
对于0中的i..代码错误:
jsonElement=jsonResult[i]as!NSDictionary
我认为swift只连接https,我这样说是因为我编写了一个swift 4 iOS应用程序,与现有的Android Java应用程序一起使用(两者都使用PHP服务器并通过json进行通信),我讨厌将整个服务器迁移到https并迁移所有Android用户。也许有办法解决这个问题,但我认为这是一个“问题”。找到导致崩溃的那行代码,因为您显示的代码中似乎没有出现该错误。没有(NS)字典提及。这是一行:jsonElement=jsonResult[i]as!有什么背景吗?因为你没有写这条线,也不知道你是怎么做到的jsonResult[i]
等于NSNull
,因此无法转换为NSDictionarySorry,我现在添加了swift文件,我是一个完全的新手,这就是为什么我忘了sorryok我做了-LarMe你可以创建一个可以连接到http或https的iOS应用程序,虽然如果你想将应用上传到苹果应用商店,他们需要https,除非你有很好的理由。这似乎是对的,我记得在我尝试发布时遇到过这样的情况,用户需要知道我的答案原则上没有错,重要的是要提前知道,不必等到交付阶段