G
G
Gravio2019-04-22 16:42:15
Data synchronization
Gravio, 2019-04-22 16:42:15

Synchronous execution of SWIFT alamofire code?

It is necessary to implement synchronous code execution, the problem is that I have not one request from alamofire, but several.

spoiler
bBf4FAo.png
func download_all_audio(lesson: LessonClass)
    {
        Mainlesson = [lesson]
        
        for (tl, l) in Mainlesson[0].cards.enumerated() {
            start_download(url: l.Audio, t:tl) {
                
            }
        }
        
        print("============")
        print(self.Mainlesson[0].cards[0].LocalAudio)
    }

func start_download(url: String, t: Int, completion: @escaping () -> Void)
    {
        guard let url = URL.init(string: url) else {
            print("error url")
            return
        }
        
        let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory)
        
        Alamofire.download(url, to: destination)
            .downloadProgress { progress in
                //print("Download Progress: \(String(progress.fractionCompleted))")
            }
            .responseData { response in
                self.Mainlesson[0].cards[t].LocalAudio = response.destinationURL!.absoluteString
        }
        
        completion()
    }

It is necessary that at the exit it fulfills all requests and then displays print (or any other action)

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
doublench21, 2019-04-24
@doublench21

Welcome to the world of DispatchQueue or OperationQueue of your choice. The first one is easier. Since the task itself is asynchronous, you will need to tighten up a bit. For DispatchQueue, you will need to use barriers, since a regular serial queue will not work.
Submit your work and we'll discuss further.

A
Alexey, 2019-04-23
@TheKnight

There are two options:
1. Write idiomatic asynchronous code using the completion handler (don't worry, it only hurts the first time). If you need to call several requests in a chain, you can nest them in the completion handler of the previous request. But in the example shown, I don't see the need for it.
2. Use appropriate libraries .
Let me remind you that locking a UI thread is a bad idea.

B
briahas, 2019-05-06
@briahas

Or, use Promises+Alamofire

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question