首页 > 解决方案 > 我如何将数据从 xcode 项目发送到个人网站,然后返回不同的数据?

问题描述

我目前正在创建一个应用程序,它将显示有关我大学校园酒吧的大量信息。此类信息包括每个酒吧的当前封面、排队长度、特色饮品和酒吧氛围。酒吧的封面、线长和气氛将由应用程序的用户手动设置。因此,如果有人走到酒吧看到封面是 15 美元并按下按钮,该应用程序将向我创建的网站发送整数“15”,然后该网站将接收它并将其插入包含其他人设置的所有封面的数组。一旦发生这种情况,我希望网站将数组返回给应用程序(或 Xcode,因为它目前正在开发中),然后它可以在其中处理和显示正确的数据。我花了数周时间学习 JavaScript、HTTP 请求、和 JSON 等等,但我仍然没有找到真正做到这一点的方法。几乎感觉就像我错过了一块拼图。

当用户在 Xcode 中按下按钮时,会调用下面的函数。它是用 Swift 编写的。

func CreateRequest()
{
guard let encoded = try? JSONEncoder().encode(15)//encoding the integer 15
else{
print("failed to encode")
return
}
let url=URL(string: "https://barmelsu.com") //this is my website link
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
request.httpBody = endoded
URLSession.shared.dataTask(with: request) //actually sending the HTTP request
{ data, response, error in
guard let data =  data else {print("No data in response \(error?.localizedDescription)."
return}
if let decoded = try? JSONDecoder().decode(Array<Int>.self, from: data)
{
print(decoded)
}
.resume()
}

正如我所说,感觉这应该是一项非常简单的任务,但我觉得我错过了一些东西。如果有人对我需要学习哪些主题有任何建议,我将不胜感激。我对网络的概念还是很陌生。

标签: jsonswiftxcodehttpnetwork-programming

解决方案


推荐阅读