简体   繁体   中英

Swift: Chain multiple network request, Alamofire

I have a question about chain more network requests (Alamofire) but the number of that requests can be sometimes 4 sometimes 9 etc, it depends on target configurations. I have one dashboard viewcontroller and that VC has 4-9 embedded VC's, everyone must fetch some data from API and that is the issue, all of them try to fetch "in the same time" but a lot of them fails, randomly.

I use semaphore for this issue but sometimes request failed, not sure why. I think one request blocks another or something like that.

For example this I have:

let dispatchQueue = DispatchQueue.global(qos: .background)
        dispatchQueue.async {
        if MDUtilites.isMediaPresent() {
                let _ = self.fetchMediaList()
                self.semaphore.wait()
                
            }
}

and I have about 10 block of codes like this and func is:

func fetchMediaList() {
    MDApiManager.sharedInstance.fetchMediaList { (dict, status) in
        switch (status) {
        case .failed(let code, _, let description):
            print("failed:")
            print(code)
            print(description)
            self.semaphore.signal()
        case .success(_, _ , _):
            print("success")
            
            if let data = dict,
                let list = data.parseWith(type: MediaBase.self)?.list {
                self.newMedia = list
                NotificationCenter.default.post(name: Notification.Name(rawValue: MEDIA_UPDATE), object: nil)
                //                    self.mediaListSections = list
                //                    self.getCategories(data: list)
            }
            self.semaphore.signal()
        case .unknown:
            print("DEBUG: unknown fetchMediaList")
            self.fetchMediaList()
        //                self.semaphore.signal()
        case .error(let aError):
            print(aError)
            self.semaphore.signal()
        }
    }
}

Can someone help to solve this issue with more requests at the same time, Semaphore sometimes works sometimes not.

It was some bug in code Semaphore works as it should

You don't need to use semaphore for your requests . Since your request are executed asynchronously / independent of one another , depending on type of request it takes time for execution. Each of your controller fetch this request when it loaded into memory . Fetch them in ViewDidLoad() . Make sure you are adding your multiple controllers correctly into your parent controller .

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