在其他与Web服务一起使用的swift文件中调用func不会返回任何内容

时间:2016-07-01 18:12:58

标签: ios swift web-services

在swift 2中当我与网络服务进行通信时,当我在按钮操作中编写这些代码时,它可以正常工作。

let alert = UIAlertController(title: "Alert", message: "Message", preferredStyle: .Alert)

    let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in })

    alert.addAction(ok);

    let request = NSMutableURLRequest(URL: NSURL(string: "http://www.myaddress.com/web-service/iostest.aspx")!)
    request.HTTPMethod = "POST"

    var postString = String();
    postString = "uid=1";
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {

            alert.title="Error"
            alert.message = "Connection error"

            dispatch_async(dispatch_get_main_queue()){
                self.presentViewController(alert, animated: true, completion: nil)
            }
            return
        }

        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
            alert.title="Error"
            alert.message = "Server error"

            dispatch_async(dispatch_get_main_queue()){
                self.presentViewController(alert, animated: true, completion: nil)
            }

        }

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)

        alert.title="Info"
        alert.message = responseString as? String

        dispatch_async(dispatch_get_main_queue()){
            self.presentViewController(alert, animated: true, completion: nil)
        }
    }
    task.resume()

正如我所说这样可以正常工作,但我想从不同的ViewControls中做到这一点我也创建了一个swift文件,其中包含一个结构和一个静态函数,该结构返回" responseString"所以我可以在视图控件中提醒它。像这样:

struct globalClass {

static func sendInfo(url: String, data: String) -> (answer: String, errorCode: Int32) {
    var res = String();
    var err = Int32();
    err = 0;
    let request = NSMutableURLRequest(URL: NSURL(string: url)!);
    request.HTTPMethod = "POST";
    let postString: String = data;
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        guard error == nil && data != nil else {
            err = 1;
            return;
        }

        if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
            err = 2;
            return;
        }

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding);
        res = (responseString as? String)!;
    }
    task.resume();
    return (res, err);
}

但是现在当我从我的按钮调用这个功能时,它会非常快地向我显示一个空的警报,似乎它没有从网络服务获得任何东西,甚至也没有尝试过。

我把它们放在按钮动作中:

@IBAction func btnData(sender: AnyObject) {

    let y: String = "uid=1";

    let res = globalClass.sendInfo("http://www.myaddress.com/web-service/iostest.aspx", data: y);

    let alert = UIAlertController(title: "", message: "", preferredStyle: .Alert);
    let OK = UIAlertAction(title: "OK", style: .Default, handler: nil);
    alert.addAction(OK);

    if (res.errorCode==0) {
        alert.title = "Info";
        alert.message = res.answer;
    } else if (res.errorCode==1) {
        alert.title = "Error";
        alert.message = "Error connecting to server";
    } else {
        alert.title = "Error";
        alert.message = "Server returned an error";
    }

    dispatch_async(dispatch_get_main_queue()){
        self.presentViewController(alert, animated: true, completion: nil);
    };

}

感谢您的帮助,

Afshin Mobayen Khiabani

2 个答案:

答案 0 :(得分:1)

static func sendInfo(url: String, data: String, completion: (answer: String, errorCode: Int32) -> ()){
//Your code..

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding);
        res = (responseString as? String)!;
     completion(answer: res, errorCode: err)
    }
    task.resume()



}

然后当你拨打sendInfo时,请这样打电话:

sendInfo(url: "your url", data: "your data") { (result, error) in

//you use your result and error values as u want.
}

答案 1 :(得分:1)

globalClass.sendInfo使用异步调用 - dataTaskWithRequest。请求的结果将在完成此方法时提供。但是,您不会等待该结果,而是尝试使用sendInfo之类的同步功能。

为了能够提供dataTaskWithRequest完成的结果,将您自己的完成放入sendInfo并在结果传递时调用此完成(闭包)。一个例子

struct GlobalClass {
    static func sendInfo(url: String, data: String, completion: (answer: String?, errorCode: Int32?) -> Void) {
        // you code here which prepares request
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
            // you parse the result here
            // you deliver the result using closure
            completion(string, error)
        }
        task.resume();
    }
}

使用示例:

func usage() {
    GlobalClass.sendInfo("url", data: "data") { (answer, errorCode) in
        // your answer and errorCode here
        // handle the result
    }
}