将Alamofire实现为DDD结构

时间:2016-02-08 05:14:43

标签: swift networking alamofire

Qustion

我有以下结构

class UITableViewController(Presentation) - >类内容(域) - > class API(Infrastructure)

Contents类通过API类获取原始数据并形成内容,然后传递给UITableViewController。

我想使用Alamofire在API类中进行网络连接。

我查看了stackoverflow,我只找到了UITableViewController直接访问API类的示例。从Presentation层直接访问Infrastructure层是我们不应该做的事情。 像这样 How to return value from Alamofire

如何将Alamofire实现为DDD结构?

我想实现类似的东西

的UITableViewController

class MyTableViewController: UITableViewController {

var contents: Contents?

override func viewDidLoad() {
    super.viewDidLoad()

    let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
    dispatch_async(dispatch_get_global_queue(priority, 0)) {
        // do some task
        self.contents = Contents.get("MyContents")
        self.tableView.reloadData()

    }
}
}

内容

class Contents: NSObject {

static func get(contentsName: String) -> Contents {
    let data = MyAPI.getRequest("https://xxxx.com/myContents")

    // Form contents
    let contents = ContentsFactory(data)

    return contents
}
}

API

class MyAPI: NSObject {

static getRequest(url) -> NSData {
    // Get and return data using alamofire
}
}

1 个答案:

答案 0 :(得分:0)

您需要处理在后台运行的get请求,而Contents的实例将立即返回。在Alamofire请求的完成处理程序中,您需要它回调Contents实例,然后回调ViewController

因此,Contents类需要在get函数上传递完成闭包,类似于:

static func get(contentsName: String, completion: (() -> Void)?) -> Contents {

此闭包必须传递给API(或通过其他技术),因此最终可以在Alamofire请求完成时调用它。此外,不是让类方法完成所有后台工作,而是在您创建的Contents实例中更好地处理它。

然后你将使用:

打电话
self.contents = Contents.get("MyContents", completion({
    dispatch_async(dispatch_get_global_queue(priority, 0)) {
        self.tableView.reloadData()
    }
}