Saving CoreData to a Web Server with Swift 3.0

2020-07-30 04:03发布

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.

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
    }
}

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

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

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.

1条回答
冷血范
2楼-- · 2020-07-30 04:27

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.

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.

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.

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()

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.

UPDATE:

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))
}

Which would output:

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
查看更多
登录 后发表回答