Best architectural approaches for building iOS networking applications (REST clients)

后端 未结 13 1140
-上瘾入骨i
-上瘾入骨i 2020-12-22 14:11

I\'m an iOS developer with some experience and this question is really interesting to me. I saw a lot of different resources and materials on this topic, but nevertheless I\

相关标签:
13条回答
  • 2020-12-22 14:45

    I want to understand basic, abstract and correct architectural approach for networking applications in iOS : there is no "the best", or "the most correct" approach for building an application architecture. It is a very creative job. You should always choose the most straightforward and extensible architecture, which will be clear for any developer, who begin to work on your project or for other developers in your team, but I agree, that there can be a "good" and a "bad" architecture.

    You said: collect the most interesting approaches from experienced iOS developers, I don't think that my approach is the most interesting or correct, but I've used it in several projects and satisfied with it. It is a hybrid approach of the ones you have mentioned above, and also with improvements from my own research efforts. I'm interesting in the problems of building approaches, which combine several well-known patterns and idioms. I think a lot of Fowler's enterprise patterns can be successfully applied to the mobile applications. Here is a list of the most interesting ones, which we can apply for creating an iOS application architecture (in my opinion): Service Layer, Unit Of Work, Remote Facade, Data Transfer Object, Gateway, Layer Supertype, Special Case, Domain Model. You should always correctly design a model layer and always don't forget about the persistence (it can significantly increase your app's performance). You can use Core Data for this. But you should not forget, that Core Data is not an ORM or a database, but an object graph manager with persistence as a good option of it. So, very often Core Data can be too heavy for your needs and you can look at new solutions such as Realm and Couchbase Lite, or build your own lightweight object mapping/persistence layer, based on raw SQLite or LevelDB. Also I advice you to familiarize yourself with the Domain Driven Design and CQRS.

    At first, I think, we should create another layer for networking, because we don't want fat controllers or heavy, overwhelmed models. I don't believe in those fat model, skinny controller things. But I do believe in skinny everything approach, because no class should be fat, ever. All networking can be generally abstracted as business logic, consequently we should have another layer, where we can put it. Service Layer is what we need:

    It encapsulates the application's business logic,  controlling transactions 
    and coordinating responses in the implementation of its operations.
    

    In our MVC realm Service Layer is something like a mediator between domain model and controllers. There is a rather similar variation of this approach called MVCS where a Store is actually our Service layer. Store vends model instances and handles the networking, caching etc. I want to mention that you should not write all your networking and business logic in your service layer. This also can be considered as a bad design. For more info look at the Anemic and Rich domain models. Some service methods and business logic can be handled in the model, so it will be a "rich" (with behaviour) model.

    I always extensively use two libraries: AFNetworking 2.0 and ReactiveCocoa. I think it is a must have for any modern application that interacts with the network and web-services or contains complex UI logic.

    ARCHITECTURE

    At first I create a general APIClient class, which is a subclass of AFHTTPSessionManager. This is a workhorse of all networking in the application: all service classes delegate actual REST requests to it. It contains all the customizations of HTTP client, which I need in the particular application: SSL pinning, error processing and creating straightforward NSError objects with detailed failure reasons and descriptions of all API and connection errors (in such case controller will be able to show correct messages for the user), setting request and response serializers, http headers and other network-related stuff. Then I logically divide all the API requests into subservices or, more correctly, microservices: UserSerivces, CommonServices, SecurityServices, FriendsServices and so on, accordingly to business logic they implement. Each of these microservices is a separate class. They, together, form a Service Layer. These classes contain methods for each API request, process domain models and always returns a RACSignal with the parsed response model or NSError to the caller.

    I want to mention that if you have complex model serialisation logic - then create another layer for it: something like Data Mapper but more general e.g. JSON/XML -> Model mapper. If you have cache: then create it as a separate layer/service too (you shouldn't mix business logic with caching). Why? Because correct caching layer can be quite complex with its own gotchas. People implement complex logic to get valid, predictable caching like e.g. monoidal caching with projections based on profunctors. You can read about this beautiful library called Carlos to understand more. And don't forget that Core Data can really help you with all caching issues and will allow you to write less logic. Also, if you have some logic between NSManagedObjectContext and server requests models, you can use Repository pattern, which separates the logic that retrieves the data and maps it to the entity model from the business logic that acts on the model. So, I advice to use Repository pattern even when you have a Core Data based architecture. Repository can abstract things, like NSFetchRequest,NSEntityDescription, NSPredicate and so on to plain methods like get or put.

    After all these actions in the Service layer, caller (view controller) can do some complex asynchronous stuff with the response: signal manipulations, chaining, mapping, etc. with the help of ReactiveCocoa primitives , or just subscribe to it and show results in the view. I inject with the Dependency Injection in all these service classes my APIClient, which will translate a particular service call into corresponding GET, POST, PUT, DELETE, etc. request to the REST endpoint. In this case APIClient is passed implicitly to all controllers, you can make this explicit with a parametrised over APIClient service classes. This can make sense if you want to use different customisations of the APIClient for particular service classes, but if you ,for some reasons, don't want extra copies or you are sure that you always will use one particular instance (without customisations) of the APIClient - make it a singleton, but DON'T, please DON'T make service classes as singletons.

    Then each view controller again with the DI injects the service class it needs, calls appropriate service methods and composes their results with the UI logic. For dependency injection I like to use BloodMagic or a more powerful framework Typhoon. I never use singletons, God APIManagerWhatever class or other wrong stuff. Because if you call your class WhateverManager, this indicates than you don't know its purpose and it is a bad design choice. Singletons is also an anti-pattern, and in most cases (except rare ones) is a wrong solution. Singleton should be considered only if all three of the following criteria are satisfied:

    1. Ownership of the single instance cannot be reasonably assigned;
    2. Lazy initialization is desirable;
    3. Global access is not otherwise provided for.

    In our case ownership of the single instance is not an issue and also we don't need global access after we divided our god manager into services, because now only one or several dedicated controllers need a particular service (e.g. UserProfile controller needs UserServices and so on).

    We should always respect S principle in SOLID and use separation of concerns, so don't put all your service methods and networks calls in one class, because it's crazy, especially if you develop a large enterprise application. That's why we should consider dependency injection and services approach. I consider this approach as modern and post-OO. In this case we split our application into two parts: control logic (controllers and events) and parameters.

    One kind of parameters would be ordinary “data” parameters. That’s what we pass around functions, manipulate, modify, persist, etc. These are entities, aggregates, collections, case classes. The other kind would be “service” parameters. These are classes which encapsulate business logic, allow communicating with external systems, provide data access.

    Here is a general workflow of my architecture by example. Let's suppose we have a FriendsViewController, which displays list of user's friends and we have an option to remove from friends. I create a method in my FriendsServices class called:

    - (RACSignal *)removeFriend:(Friend * const)friend
    

    where Friend is a model/domain object (or it can be just a User object if they have similar attributes). Underhood this method parses Friend to NSDictionary of JSON parameters friend_id, name, surname, friend_request_id and so on. I always use Mantle library for this kind of boilerplate and for my model layer (parsing back and forward, managing nested object hierarchies in JSON and so on). After parsing it calls APIClient DELETE method to make an actual REST request and returns Response in RACSignal to the caller (FriendsViewController in our case) to display appropriate message for the user or whatever.

    If our application is a very big one, we have to separate our logic even clearer. E.g. it is not always good to mix Repository or model logic with Service one. When I described my approach I had said that removeFriend method should be in the Service layer, but if we will be more pedantic we can notice that it better belongs to Repository. Let's remember what Repository is. Eric Evans gave it a precise description in his book [DDD]:

    A Repository represents all objects of a certain type as a conceptual set. It acts like a collection, except with more elaborate querying capability.

    So, a Repository is essentially a facade that uses Collection style semantics (Add, Update, Remove) to supply access to data/objects. That's why when you have something like: getFriendsList, getUserGroups, removeFriend you can place it in the Repository, because collection-like semantics is pretty clear here. And code like:

    - (RACSignal *)approveFriendRequest:(FriendRequest * const)request;
    

    is definitely a business logic, because it is beyond basic CRUD operations and connect two domain objects (Friend and Request), that's why it should be placed in the Service layer. Also I want to notice: don't create unnecessary abstractions. Use all these approaches wisely. Because if you will overwhelm your application with abstractions, this will increase its accidental complexity, and complexity causes more problems in software systems than anything else

    I describe you an "old" Objective-C example but this approach can be very easy adapted for Swift language with a lot more improvements, because it has more useful features and functional sugar. I highly recommend to use this library: Moya. It allows you to create a more elegant APIClient layer (our workhorse as you remember). Now our APIClient provider will be a value type (enum) with extensions conforming to protocols and leveraging destructuring pattern matching. Swift enums + pattern matching allows us to create algebraic data types as in classic functional programming. Our microservices will use this improved APIClient provider as in usual Objective-C approach. For model layer instead of Mantle you can use ObjectMapper library or I like to use more elegant and functional Argo library.

    So, I described my general architectural approach, which can be adapted for any application, I think. There can be a lot more improvements, of course. I advice you to learn functional programming, because you can benefit from it a lot, but don't go too far with it too. Eliminating excessive, shared, global mutable state, creating an immutable domain model or creating pure functions without external side-effects is, generally, a good practice, and new Swift language encourages this. But always remember, that overloading your code with heavy pure functional patterns, category-theoretical approaches is a bad idea, because other developers will read and support your code, and they can be frustrated or scary of the prismatic profunctors and such kind of stuff in your immutable model. The same thing with the ReactiveCocoa: don't RACify your code too much, because it can become unreadable really fast, especially for newbies. Use it when it can really simplify your goals and logic.

    So, read a lot, mix, experiment, and try to pick up the best from different architectural approaches. It is the best advice I can give you.

    0 讨论(0)
  • 2020-12-22 14:48

    Because all iOS apps are different, I think there are different approaches here to consider, but I usually go this way:
    Create a central manager (singleton) class to handle all API requests (usually named APICommunicator) and every instance method is an API call. And there is one central (non-public) method:

    -(RACSignal *)sendGetToServerToSubPath:(NSString *)path withParameters:(NSDictionary *)params;

    For the record, I use 2 major libraries/frameworks, ReactiveCocoa and AFNetworking. ReactiveCocoa handles async networking responses perfectly, you can do (sendNext:, sendError:, etc.).
    This method calls the API, gets the results and sends them through RAC in 'raw' format (like NSArray what AFNetworking returns).
    Then a method like getStuffList: which called the above method subscribes to it's signal, parses the raw data into objects (with something like Motis) and sends the objects one by one to the caller (getStuffList: and similar methods also return a signal that the controller can subscribe to).
    The subscribed controller receives the objects by subscribeNext:'s block and handles them.

    I tried many ways in different apps but this one worked the best out of all so I've been using this in a few apps recently, it fits both small and big projects and it's easy to extend and maintain if something needs to be modified.
    Hope this helps, I'd like to hear others' opinions about my approach and maybe how others think this could be maybe improved.

    0 讨论(0)
  • 2020-12-22 14:48

    Try https://github.com/kevin0571/STNetTaskQueue

    Create API requests in separated classes.

    STNetTaskQueue will deal with threading and delegate/callback.

    Extendable for different protocols.

    0 讨论(0)
  • 2020-12-22 14:52

    To my mind all software architecture is driven by need. If this is for learning or personal purposes, then decide the primary goal and have that drive the architecture. If this is a work for hire, then the business need is paramount. The trick is to not let shiny things distract you from the real needs. I find this hard to do. There are always new shiny things appearing in this business and lots of them are not useful, but you can't always tell that up front. Focus on the need and be willing to abandon bad choices if you can.

    For example, I recently did a quick prototype of a photo sharing app for a local business. Since the business need was to do something quick and dirty, the architecture ended up being some iOS code to pop up a camera and some network code attached to a Send Button that uploaded the image to a S3 store and wrote to a SimpleDB domain. The code was trivial and the cost minimal and the client has an scalable photo collection accessible over the web with REST calls. Cheap and dumb, the app had lots of flaws and would lock the UI on occasion, but it would be a waste to do more for a prototype and it allows them to deploy to their staff and generate thousands of test images easily without performance or scalability concerns. Crappy architecture, but it fit the need and cost perfectly.

    Another project involved implementing a local secure database which synchronizes with the company system in the background when the network is available. I created a background synchronizer that used RestKit as it seemed to have everything I needed. But I had to write so much custom code for RestKit to deal with idiosyncratic JSON that I could have done it all quicker by writing my own JSON to CoreData transformations. However, the customer wanted to bring this app in house and I felt that RestKit would be similar to the frameworks that they used on other platforms. I waiting to see if that was a good decision.

    Again, the issue to me is to focus on the need and let that determine the architecture. I try like hell to avoid using third party packages as they bring costs that only appears after the app has been in the field for a while. I try to avoid making class hierarchies as they rarely pay off. If I can write something in a reasonable period of time instead of adopting a package that doesn't fit perfectly, then I do it. My code is well structured for debugging and appropriately commented, but third party packages rarely are. With that said, I find AF Networking too useful to ignore and well structured, well commented, and maintained and I use it a lot! RestKit covers a lot of common cases, but I feel like I've been in a fight when I use it, and most of the data sources I encounter are full of quirks and issues that are best handled with custom code. In my last few apps I just use the built in JSON converters and write a few utility methods.

    One pattern I always use is to get the network calls off the main thread. The last 4-5 apps I've done set up a background timer task using dispatch_source_create that wakes up every so often and does network tasks as needed. You need to do some thread safety work and make sure that UI modifying code gets sent to the main thread. It also helps to do your onboarding/initialization in such a way that the user doesn't feel burdened or delayed. So far this has been working rather well. I suggest looking into these things.

    Finally, I think that as we work more and as the OS evolves, we tend to develop better solutions. It has taken me years to get over my belief that I have to follow patterns and designs that other people claim are mandatory. If I am working in a context where that is part of the local religion, ahem, I mean the departmental best engineering practices, then I follow the customs to the letter, that's what they are paying me for. But I rarely find that following older designs and patterns is the optimal solution. I always try to look at the solution through the prism of the business needs and build the architecture to match it and keep things as simple as they can be. When I feel like there isn't enough there, but everything works correctly, then I'm on the right track.

    0 讨论(0)
  • 2020-12-22 14:56

    I avoid singletons when designing my applications. They are a typical go to for a lot of people but I think you can find more elegant solutions elsewhere. Typically what I do is a build out my entities in CoreData and then put my REST code in an NSManagedObject category. If for instance I wanted to create and POST a new User, I'd do this:

    User* newUser = [User createInManagedObjectContext:managedObjectContext];
    [newUser postOnSuccess:^(...) { ... } onFailure:^(...) { ... }];
    

    I use RESTKit for the object mapping and initialize it at start up. I find routing all of your calls through a singleton to be a waste of time and adds a lot of boilerplate that isn't needed.

    In NSManagedObject+Extensions.m:

    + (instancetype)createInContext:(NSManagedObjectContext*)context
    {
        NSAssert(context.persistentStoreCoordinator.managedObjectModel.entitiesByName[[self entityName]] != nil, @"Entity with name %@ not found in model. Is your class name the same as your entity name?", [self entityName]);
        return [NSEntityDescription insertNewObjectForEntityForName:[self entityName] inManagedObjectContext:context];
    }
    

    In NSManagedObject+Networking.m:

    - (void)getOnSuccess:(RESTSuccess)onSuccess onFailure:(RESTFailure)onFailure blockInput:(BOOL)blockInput
    {
        [[RKObjectManager sharedManager] getObject:self path:nil parameters:nil success:onSuccess failure:onFailure];
        [self handleInputBlocking:blockInput];
    }
    

    Why add extra helper classes when you can extend the functionality of a common base class through categories?

    If you're interested in more detailed info on my solution let me know. I'm happy to share.

    0 讨论(0)
  • 2020-12-22 14:57

    I use the approach that I've gotten from here: https://github.com/Constantine-Fry/Foursquare-API-v2. I've rewritten that library in Swift and you can see the architectural approach from these parts of the code:

    typealias OpertaionCallback = (success: Bool, result: AnyObject?) -> ()
    
    class Foursquare{
        var authorizationCallback: OperationCallback?
        var operationQueue: NSOperationQueue
        var callbackQueue: dispatch_queue_t?
    
        init(){
            operationQueue = NSOperationQueue()
            operationQueue.maxConcurrentOperationCount = 7;
            callbackQueue = dispatch_get_main_queue();
        }
    
        func checkIn(venueID: String, shout: String, callback: OperationCallback) -> NSOperation {
            let parameters: Dictionary <String, String> = [
                "venueId":venueID,
                "shout":shout,
                "broadcast":"public"]
            return self.sendRequest("checkins/add", parameters: parameters, httpMethod: "POST", callback: callback)
        }
    
        func sendRequest(path: String, parameters: Dictionary <String, String>, httpMethod: String, callback:OperationCallback) -> NSOperation{
            let url = self.constructURL(path, parameters: parameters)
            var request = NSMutableURLRequest(URL: url)
            request.HTTPMethod = httpMethod
            let operation = Operation(request: request, callbackBlock: callback, callbackQueue: self.callbackQueue!)
            self.operationQueue.addOperation(operation)
            return operation
        }
    
        func constructURL(path: String, parameters: Dictionary <String, String>) -> NSURL {
            var parametersString = kFSBaseURL+path
            var firstItem = true
            for key in parameters.keys {
                let string = parameters[key]
                let mark = (firstItem ? "?" : "&")
                parametersString += "\(mark)\(key)=\(string)"
                firstItem = false
            }
        return NSURL(string: parametersString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding))
        }
    }
    
    class Operation: NSOperation {
        var callbackBlock: OpertaionCallback
        var request: NSURLRequest
        var callbackQueue: dispatch_queue_t
    
        init(request: NSURLRequest, callbackBlock: OpertaionCallback, callbackQueue: dispatch_queue_t) {
            self.request = request
            self.callbackBlock = callbackBlock
            self.callbackQueue = callbackQueue
        }
    
        override func main() {
            var error: NSError?
            var result: AnyObject?
            var response: NSURLResponse?
    
            var recievedData: NSData? = NSURLConnection.sendSynchronousRequest(self.request, returningResponse: &response, error: &error)
    
            if self.cancelled {return}
    
            if recievedData{
                result = NSJSONSerialization.JSONObjectWithData(recievedData, options: nil, error: &error)
                if result != nil {
                    if result!.isKindOfClass(NSClassFromString("NSError")){
                        error = result as? NSError
                }
            }
    
            if self.cancelled {return}
    
            dispatch_async(self.callbackQueue, {
                if (error) {
                    self.callbackBlock(success: false, result: error!);
                } else {
                    self.callbackBlock(success: true, result: result!);
                }
                })
        }
    
        override var concurrent:Bool {get {return true}}
    }
    

    Basically, there is NSOperation subclass that makes the NSURLRequest, parses JSON response and adds the callback block with the result to the queue. The main API class constructs NSURLRequest, initialises that NSOperation subclass and adds it to the queue.

    0 讨论(0)
提交回复
热议问题