Swift Blocks Not Working

Swift blocks not working

It has something to do with how Swift implement closure. You need to use @convention(block) to annotate that the closure is ObjC block. Use unsafeBitCast to force cast it

var block : @convention(block) (NSString!) -> Void = {
(string : NSString!) -> Void in
println("test")
}

ctx.setObject(unsafeBitCast(block, AnyObject.self), forKeyedSubscript: "test")

from REPL

swift
Welcome to Swift! Type :help for assistance.
1> import Foundation
2> var block : @convention(block)(NSString!) -> Void = {(string : NSString!) -> Void in println("test")}
block: @convention(block)(NSString!) -> Void =
3> var obj: AnyObject = reinterpretCast(block) as AnyObject
obj: __NSMallocBlock__ = {} // familiar block type

Swift dispatch queue block not running

If you can't debug yourself, NEVER USE try?. With more experience, I'd say that we tend to not use try?, but sometimes we do. But when we write try?, we are able to find an possible issue, ie debug if needed.

Let's do a proper try then, with a do/catch:

do { 
let response = try JSONDecoder().decode([Recipe].self, from: data
DispatchQueue.main.async {
self.recipes = response
}
} catch {
print("Oops, there was en error while decoding: \(error)") // and not error.localizedDescription as it's more for users than developpers, so you'll skip all the useful informations
}

And read the output.

Going further?

Don't believe what's the API is supposed to return.

I've seen plenty and plenty of questions where the returned values was an error message, a XML Error message, a JSON Error message, an HTML Error message, and a JSON value missing, or of bad type, etc. And that, your JSONDecoder wasn't expecting it...

Reasons could be various, from bad/missing parameters, bad/missing APIKey, server down, bad/missing header, etc.

But, then, print the returned value.

print(String(data: data, encoding: .utf8) ?? "No data found")

So print it directly when you get it, or at least in the catch:

} catch {
print("Oops, there was en error while decoding: \(error)") // and not error.localizedDescription as it's more for users than developpers, so you'll skip all the useful informations
print("While getting response stringified: \(String(data: data, encoding: .utf8) ?? "No data found")")
}

If you don't understand the error message output, it's okay, there is no shame about it. But your first job is to get that error message. You can share it on SO if you don't understand it, you might get help with that. But currently, we can't guess what's wrong with your code.

Creating block in Swift is not working

Another problem, in addition to the issue pointed out by Mrwerdo is that this code:

var objJsonParser:JsonParser?

objJsonParser?.Getdata(str as String, RequsetedParameter:Dictionary, BLOCK: {
(dict, error) in
print("success")
})

doesn't actually do anything and won't complain because objJsonParser is nil unless you assign something to it and the ? in the invocation means that GetData will do nothing because the object is nil.

Swift HTTP Request Completion Block not Working Properly

As Tarun indicated, your executable is exiting before your call can be made. One way you can wait before exiting is to use a DispatchGroup like the following.

let session = URLSession.shared
let url = URL(string: "https://jsonplaceholder.typicode.com/posts")!
let group = DispatchGroup()
group.enter()
let task = session.dataTask(with: url, completionHandler: { data, response, error in
// Check the response
print(error)
print(response)
group.leave()
})
task.resume()
group.wait()

Why is my Objective-C block not showing up when passed to Swift function?

It turns out although Obj-c optimization was off, the Swift optimization was on, and this was causing the problem. I don't suppose it should, but this seems to be the case.

swift completion block does not execute tasks in order?

Call the completion inside the observe block...

func getInfoFromDatabase(completion: (_ success: Bool) -> Void) {
stoRef.observe(.value, with: { snapshot in
self.caption = (snapshot.value as? NSDictionary)?["Caption"] as! String
self.views = (snapshot.value as? NSDictionary)?["Views"] as! Int
self.votes = (snapshot.value as? NSDictionary)?["Votes"] as! Int

print(self.views)
print(self.votes)
print(self.caption)
// these variables get printed correctly in console
completion(true)
})
}

Swift: Firebase Storage Code Block Not Executing

Firebase is asynchronous and firebase data is only valid within the closure following the firebase function. In a nutshell, code is faster than the internet and it takes time for data to download.

Here's an abbreviated version of your code... note the comments

func updateCurrentUser() {
var downloadedImages : [UIImage?] = []
for i in 0...8 {
imageRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
//firebase data is ONLY valid here so append each image to an array
self.currentUser.images.append(downloadedImage)
}
}

//the following line will execute WAY before the images are downloaded
// so self.currentUser.images will always be empty
self.currentUser.images = downloadedImages
}

You're probably going to want to use a completion handler as well. See my answer this question for further reading



Related Topics



Leave a reply



Submit