多个网站的多个Alamofire请求的正确模型 [英] Proper model for multiple Alamofire requests for multiple websites

查看:106
本文介绍了多个网站的多个Alamofire请求的正确模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Alamofire抓取网页中的某些数据,例如新闻。新闻是具有标题,内容,图片,日期,作者等内容的通用对象。但是,对于每个网站,我使用不同的方法。对于某些人,我使用json;对于其他人,我使用hpple提取数据。如何为每个网站创建某种服务。我应该为每个网站创建不同的服务,还是有更好的方法为每个网站使用某种通用功能模板。像

I am using Alamofire to scrap web pages for some data, let’s say News. News is a generic object with something like title, content, picture, date, author etc. However for each web site, I use different method. For some I use json for others I use hpple to extract the data. How can I create a some kind of service for each website. Should I create different Services for each web site or is there a better way to use some kind of generic function templates for each web site. Like

Login()
Fetch()
Populate()
return News(…..)

然后在创建新闻并填充表格视图之后,如何刷新News对象?由于News是通用的,因此无法知道是谁使用哪种方法创建的。

Then after I create the news and populate the tableview, how can I refresh the News object? Since News is generic, it can’t know who created it with which method.

推荐答案

有很多方法可以设计这种类型的抽象。如果可能的话,我倾向于尽可能地简化我的建筑设计。这里的一个很好的模式是将 Service 对象与类方法一起使用,以处理调用您的不同服务,解析结果以及调用成功或失败关闭的过程。

There are many ways to design this type of abstraction. I tend to lean towards simplicity as much as possible in my architectural designs if possible. A great pattern here is to use a Service object with class methods to handle calling your different services, parsing the result and calling a success or failure closure.

您还可以使用不会将成功和失败分成两部分的完成处理程序,但是您需要在调用者对象中处理我并不喜欢的失败或成功。这是 Service 设计的示例。

You can also use a completion handler that doesn't split the success and failure into two things, but then you need to handle the failure or success in your caller objects which I don't really like. Here's an example of the Service design in action.

FirstNewsService

import Alamofire

struct News {
    let title: String
    let content: String
    let date: NSDate
    let author: String
}

class FirstNewsService {

    typealias NewsSuccessHandler = ([News]) -> Void
    typealias NewsFailureHandler = (NSHTTPURLResponse?, AnyObject?, NSError?) -> Void

    // MARK: - Fetching News Methods

    class func getNews(#success: NewsSuccessHandler, failure: NewsFailureHandler) {
        login(
            success: { apiKey in
                FirstNewsService.fetch(
                    apiKey: apiKey,
                    success: { news in
                        success(news)
                    },
                    failure: { response, json, error in
                        failure(response, json, error)
                    }
                )
            },
            failure: { response, json, error in
                failure(response, json, error)
            }
        )
    }

    // MARK: - Private - Helper Methods

    private class func login(#success: (String) -> Void, failure: (NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) {
        let request = Alamofire.request(.GET, "login/url")
        request.responseJSON { _, response, json, error in
            if let error = error {
                failure(response, json, error)
            } else {
                // NOTE: You'll need to parse here...I would suggest using SwiftyJSON
                let apiKey = "12345678"
                success(apiKey)
            }
        }
    }

    private class func fetch(
        #apiKey: String,
        success: ([News]) -> Void,
        failure: (NSHTTPURLResponse?, AnyObject?, NSError?) -> Void)
    {
        let request = Alamofire.request(.GET, "fetch/url")
        request.responseJSON { _, _, json, error in
            if let error = error {
                failure(response, json, error)
            } else {
                // NOTE: You'll need to parse here...I would suggest using SwiftyJSON
                let news = [News]()
                success(news)
            }
        }
    }
}

在视图控制器内部

override func viewDidLoad() {
    super.viewDidLoad()

    FirstNewsService.getNews(
        success: { news in
            // Do something awesome with that news
            self.tableView.reloadData()
        },
        failure: { response, json, error in
            // Be flexible here...do you want to retry, pull to refresh, does it matter what the response status code was?
            println("Response: \(response)")
            println("Error: \(error)")
        }
    )
}

可以随意修改设计,但是您希望根据使用情况对其进行定制。这些模式都不是一成不变的。它只是为您提供一种构建不同服务的通用方法。 @mattt在Alamofire 自述文件中也有一些非常酷的模式(路由器和CRUD),我强烈建议阅读通过。虽然它们肯定更复杂,但仍然需要 Service 类型的对象以最大化代码重用。

Feel free to mod the design however you like to tailor it to your use cases. None of this pattern is set in stone. It just gives you a common way to construct different services. @mattt also has some really cool patterns (Router and CRUD) in the Alamofire README which I would highly recommend reading through. They are definitely more complicated though and still require a Service type of object to maximize code reuse.

希望这会有所帮助阐明了一些想法。

Hopefully that helps shed some light.

这篇关于多个网站的多个Alamofire请求的正确模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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