我正在尝试在Swift中创建Block。
我已经像这样创建了类和声明的块
typealias JSONParserBlock = (dict:NSDictionary?,error:NSError?) -> Void
变量声明:
var block: JSONParserBlock!
和功能:
func Getdata(WebService: String, RequsetedParameter Param:NSDictionary?, BLOCK: JSONParserBlock!) -> Void
{}
但我的问题是当我从另一个类调用此函数时,此函数不会执行
函数调用是这样的:
var objJsonParser:JsonParser?
objJsonParser?.Getdata(str as String, RequsetedParameter:Dictionary, BLOCK:
{ (dict, error) in
print("success")
})
自定义类代码
import UIKit
class JsonParser: NSObject,NSURLConnectionDelegate
{
typealias JSONParserBlock = (dict:NSDictionary?,error:NSError?) -> Void
var block: JSONParserBlock!
var Data:NSMutableData?=nil
var delegate:JsonParserDelegate?
var DICT:NSDictionary!
var error: NSErrorPointer=nil
func Getdata(WebService: String, RequsetedParameter Param:NSDictionary?, BLOCK: JSONParserBlock!) -> Void
{
self.block=BLOCK;
Data = NSMutableData()
let urlPath: String = "http://192.168.13.2/freshbakala/admin/json/GetCategory.php"
let url: NSURL = NSURL(string: urlPath)!
let request: NSURLRequest = NSURLRequest(URL: url)
let connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: true)!
connection.start()
}
func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!)
{
self.Data = NSMutableData()
}
func connection(connection: NSURLConnection!, didReceiveData data: NSData!)
{
self.Data?.appendData(data)
}
func connectionDidFinishLoading(connection: NSURLConnection!)
{
let error:NSError
let jsonresult:NSDictionary
print("Response is received")
do
{
jsonresult = try NSJSONSerialization.JSONObjectWithData(self.Data!, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
print(jsonresult)
block(dict: jsonresult,error: nil)
}
catch
{
}
}
}
答案 0 :(得分:1)
您需要在GetData
函数中调用闭包。这样的事情应该做:
func Getdata(WebService: String, RequsetedParameter Param:NSDictionary?, BLOCK: JSONParserBlock!) -> Void
{
let dict: NSDictionary? = nil // set these to something meaningful
let error: NSError? = nil
BLOCK(dict: dict, error: error) // call the closure
}
答案 1 :(得分:1)
除Mrwerdo指出的问题外,另一个问题是此代码:
var objJsonParser:JsonParser?
objJsonParser?.Getdata(str as String, RequsetedParameter:Dictionary, BLOCK: {
(dict, error) in
print("success")
})
实际上并没有做任何事情并且不会抱怨因为objJsonParser是nil,除非你为它分配了一些东西而且调用中的?
意味着GetData
什么都不做因为对象是零。