简体   繁体   中英

iOS REST design pattern advice

I'd like some input on whether there is a better design pattern to use for my iOS app, which uses a REST model to communicate asynchronously with a Django back end.

The server can presently return three types of responses to requests:

  • a JSON object
  • a server status code integer
  • a long Django error message

When an action is performed in the iOS app that requires data from the server, my design pattern looks like this:

  • An observer is added to notification center, specifying a method that can process the server response
  • The method puts together and sends a NSURLConnection
  • A NSURLConnection delegate method receives the response, does some interpretation to check what kind of server response it is, and then posts the appropriate notification to the notification center
  • This triggers the response method to run, processing the response

My issue with this pattern is that there are a large number of methods written to send and receive individual request and response types. For instance, if I am requesting an item list, I need to add several observers to the notification center, one to process a user list, one to process a blank user list, and one to process errors. Then I need to write custom methods for each one of those three to perform the appropriate actions and remove the observers, based on what kind of response the server sends.

Furthermore, the NSURLConnection delegate ends up being fairly complex, because I'm trying to interpret what type of a response was received (what types of items were in the list received?) without much context of what was requested, to make sure I don't call the wrong response method when a server message comes back.

I am fairly new to both iOS programming and to REST programming, so I may be missing something obvious. Any advice or links to resources is appreciated.

I'd initially look at using RestKit to abstract your code away from the network comms so you can worry more about the data model and high level requests. Secondly, I wouldn't use notifications for this as it will likely get messy and be very hard to manage multiple simultaneous requests - delegation or block callbacks will be much better for this.

Your REST implementation is mostly server side, and emprirically you'd be passing and receiving binary. There are factors to consider, including whether you are utilizing HTTP.

Working with JSON with NSJSONSerialization class, and NSURLConnection keeps your program more lean and mean.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM