基本上,我是在我的swift应用中创建一个登录视图控制器,用于验证和登录用户。
这是应用程序通过POST HTTP请求进行请求和处理的方式:
import Foundation
enum MyResult<T, E: Error> {
case success(T)
case failure(E)
}
class NetworkingService {
let baseUrl = "https://example/example/login.php"
func handleResponse(for request: URLRequest,
completion: @escaping (Result<User, Error>) -> Void) {
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
DispatchQueue.main.async {
guard let unwrappedResponse = response as? HTTPURLResponse else {
completion(.failure(NetworkingError.badResponse))
return
}
print(unwrappedResponse.statusCode)
switch unwrappedResponse.statusCode {
case 200 ..< 300:
print("success")
default:
print("failure")
}
if let unwrappedError = error {
completion(.failure(unwrappedError))
return
}
if let unwrappedData = data {
do {
let json = try JSONSerialization.jsonObject(with: unwrappedData, options: [])
print(json)
if let user = try? JSONDecoder().decode(User.self, from: unwrappedData) {
completion(.success(user))
} else {
let errorResponse = try JSONDecoder().decode(ErrorResponse.self, from: unwrappedData)
completion(.failure(errorResponse))
}
} catch {
completion(.failure(error))
}
}
}
}
task.resume()
}
func request(endpoint: String,
parameters: [String: Any],
completion: @escaping (Result<User, Error>) -> Void) {
guard let url = URL(string: baseUrl + endpoint) else {
completion(.failure(NetworkingError.badUrl))
return
}
var request = URLRequest(url: url)
var components = URLComponents()
var queryItems = [URLQueryItem]()
for (key, value) in parameters {
let queryItem = URLQueryItem(name: key, value: String(describing: value))
queryItems.append(queryItem)
}
components.queryItems = queryItems
let queryItemData = components.query?.data(using: .utf8)
request.httpBody = queryItemData
request.httpMethod = "POST"
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
handleResponse(for: request, completion: completion)
}
func request(endpoint: String,
loginObject: Login,
completion: @escaping (Result<User, Error>) -> Void) {
guard let url = URL(string: baseUrl + endpoint) else {
completion(.failure(NetworkingError.badUrl))
return
}
var request = URLRequest(url: url)
do {
let loginData = try JSONEncoder().encode(loginObject)
request.httpBody = loginData
} catch {
completion(.failure(NetworkingError.badEncoding))
}
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
handleResponse(for: request, completion: completion)
}
}
enum NetworkingError: Error {
case badUrl
case badResponse
case badEncoding
}
结构如下:
import UIKit
struct User: Decodable {
let id: Int
let name: String
let username: String
}
因为我正在使用mySQL数据库,所以我使用php脚本来生成从输入中获取参数的JSON。
这是JSON的样子:
[
{
"id": "3",
"name": "KevinName",
"username": "kName"
}
]
状态码返回成功200,但没有数据加载到应用程序中,并且出现错误
由于格式不正确,无法读取数据
我相信它与创建JSON的PHP脚本有关
<?php
$con=mysqli_connect("localhost","username","password","db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Equipment'
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT id, driver_name, username FROM table1 WHERE (username = '$username') and password = '$password' ";
if ($result = mysqli_query($con, $sql))
{
// Create temporary connection
$resultArray = array();
$tempArray = array();
// Look through each row
while($row = $result->fetch_object())
{
$tempArray = $row;
array_push($resultArray, $tempArray);
}
echo json_encode($resultArray);
}
mysqli_close($con);
?>