使用Swift 3.0将CoreData保存到Web服务器 [英] Saving CoreData to a Web Server with Swift 3.0

查看:92
本文介绍了使用Swift 3.0将CoreData保存到Web服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题与以下内容有关:与Web进行快速核心数据同步服务器

This question is related to: Swift Core Data Sync With Web Server.

我已按照上面问题中提到的步骤进行操作,但是我无法执行第三步骤到我当前的项目。

I have followed the steps that have been mentioned in the question above however I am unable to apply the third step to my current project.

我目前有一个叫做Records的课程

I currently have a class called Records

class Records {

    static let shared = Records()

    var records = [Record]()
    let context = PersistenceServce.context
    let request = NSFetchRequest<Record>(entityName: "Record")

    func recordData() -> [Record] {

        do {
            records = try context.fetch(Record.fetchRequest())
        }catch {
            print("Error fetching data from CoreData")
        }

        return records
    }
}

,这就是我如何在tableViewController上显示数据。

and here is how I display the data on my tableViewController.

func getData() {
    records = Records.shared.recordData()
    self.tableView.reloadData()
}

我确实知道如何将数据保存到Web服务器,如本教程所述: https://www.simplifiedios.net/swift-php-mysql-tutorial/ 以及检查Internet连接。但是我不确定如何将其应用于涉及多个数据的CoreData。
如果有人可以指导我寻求解决方案或解释如何实现这一目标,我将不胜感激。

I do know how save data to a web server as this tutorial explains: https://www.simplifiedios.net/swift-php-mysql-tutorial/ as well as check for internet connection. However I am unsure how to apply it to the CoreData where there are multiple data involved. If anyone could direct me to a solution or an explain how this can be achieved I'd very much appreciate it.

推荐答案

您链接的问题不是试图解释如何与Web服务器通信。它说明了如何在核心数据中存储数据以及如何以知道哪些记录已发送到Web服务器的方式对其进行标记/标记。

The question that you have linked is not trying to explain how to communicate with a web server. It is explaining how to store data in core data and tag/mark it in a way that you know which records have been sent to the web server or not.

因此,谓词将获取所有尚未发送到Web服务器的记录,并允许您在有Internet连接时将其发送。

So the Predicate will fetch all records that have not been sent to the web server and allow you to send them when you have an internet connection available.

与Web服务器通信可能是一个广泛的话题,并且将取决于您的Web服务器和API设置,因此在此不做过多的解释。我向您推荐了一些免费的在线资源,这些资源将帮助您了解Swift中的联网。

Communicating with a web server can be a broad topic and will depend on your web server and API setup, so it is too much to explain here fully. I refer you to some free online resources that will help you understand networking in Swift.

  • Udacity - Networking with Swift
  • Ray Wenderlich - Alamofire Tutorial
  • Stack Overflow - Swift POST Request

这是来自上述StackOverflow答案的POST请求示例

Here is an example of a POST Request from the StackOverflow answer above

var request = URLRequest(url: URL(string: "http://test.tranzporthub.com/street45/customer_login.php")!)
request.httpMethod = "POST"
let postString = "user_id=chaitanya3191@gmail.com&password=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服务器,然后Web服务器就可以使用它执行任何操作。

Using code similar to this, you should be able to send data to your web server, then your web server can do whatever it likes with it.

更新:

要将参数编码为JSON,可以使用以下代码作为指导

To encode your parameters to JSON you can use the following code as a guide

var dictionary = [
    "username": "Test User",
    "password": "Password"
]

if let jsonData = try? JSONSerialization.data(withJSONObject: dictionary, options: []) {
    // jsonData is a byte sequence, to view it you would need to convert to string
    print(String(bytes: jsonData, encoding: String.Encoding.utf8))
}

哪个会输出:


Optional( {\ username\:\ Test User\,\ password\:\ Password \})

Optional("{\"username\":\"Test User\",\"password\":\"Password\"}")

注意:您将其作为数据发送,而不是字符串版本。因此您的代码可能如下所示:

Note: you would send it as data, not the string version. so your code might look like this:

request.httpBody = jsonData

这篇关于使用Swift 3.0将CoreData保存到Web服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆