Statik
Statik

Reputation: 342

How can I retain a local variable that is set in a completion block?

I have a function that takes an URL and returns a file URL asynchronously, when I print the value of fileURL inside the completion block it prints out perfectly, but the variable (fileURL) does not retain the value outside the completion block

FileFactory.FetchFileWithURL(workingURL, completionHandler: { (url) ->    Void in
            fileURL = url
            print(fileURL) //prints valid URLs

        })

print(fileURL) //prints nil

fileURL is defined as:-
var fileURL:String?

How can I make sure, that fireURL retains the value it got from completionblock?

EDIT:

Found similar question, but unfortunately it's in objc here

Is there any equivalent of Objective-C's __block in swift

Upvotes: 2

Views: 1076

Answers (2)

W.K.S
W.K.S

Reputation: 10095

FetchWithURL is an asynchronous function. fileUrl is instantiated in the completionHandler which itself is called only after the asynchronous task has been completed. Therefore, it simply isn't possible to use a value that doesn't exist yet.

Any operation that needs to be done with fileUrl must be done in the same completionHandler.

FileFactory.FetchFileWithURL(workingURL, completionHandler: { (url) ->    Void in
            fileURL = url
            print(fileURL) //prints valid URLs
            //other operations with fileURL
})

Upvotes: 0

Warif Akhand Rishi
Warif Akhand Rishi

Reputation: 24248

Call a new function inside the block. Do what you want to do with fileURL inside the new method.

FileFactory.FetchFileWithURL(workingURL, completionHandler: { (url) ->    Void in
        fileURL = url
        print(fileURL) //prints valid URLs
        doSomethingWithFileUrl(url)
    })

Upvotes: 3

Related Questions