Web Service Handler类困难

时间:2016-03-27 19:50:33

标签: json swift web-services asynchronous

我甚至不愿意这样做,因为那里有很多很棒的内容,但是我一直在追捕和追捕,而且我很难找到将Web服务处理程序与创建模型分开的好例子。基本上我有一个类,它具有准备HTTP请求的函数,发出HTTP请求,然后解析JSON对象并使其成为NS字典。不幸的是,由于makeRequest()的完成处理程序的性质,我从JSON对象获得了nils。我对swift,回调和一般的API通信仍然很陌生。任何帮助将不胜感激。

import Foundation

class JSONService
{
    let session = NSURLSession.sharedSession()

    var url : NSURL;
    var requestARGs : NSString;

    var request : NSMutableURLRequest!;
    //var response : NSHTTPURLResponse;
    var JSONdata : NSData!;

    var ModelFromJSON : NSDictionary!;

    //var responseString : NSString = ""

    init(URL : NSURL, ReqARGs : NSString)
    {
        url = URL
        requestARGs = ReqARGs;

        request = setupRequest(url, RequestARGs:requestARGs)

        makeRequest() {
            (response) in
            if let responseData = response as? NSData {
                self.JSONdata = responseData
            }
        }

        returnModel(JSONdata)

    }

    func setupRequest(URL: NSURL, RequestARGs: NSString) -> NSMutableURLRequest {
        let request = NSMutableURLRequest(URL: URL)
        request.HTTPMethod = "POST"
        let postString = RequestARGs
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
        return request
        }

    func makeRequest(completion: (NSData) -> ()) {
        session.dataTaskWithRequest(self.request) { data, response, error in
            self.JSONdata = data
            guard error == nil && data != nil
                else {
                // Networking Error
                print("error=\(error)")
                return
            }

            if let httpStatus = response as? NSHTTPURLResponse where httpStatus.statusCode != 200 {
                print("Network Error, the Status Code is \(httpStatus.statusCode)")
                print("response = \(response)")
            }

            completion(data!)
            //self.JSONdata = data;
            //self.responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)!

            //print("responseString = \(self.responseString)")
        }.resume()

    }

    func returnModel(data : NSData?) {

        if let responseData = data {
            do {
                let json = try
                    NSJSONSerialization.JSONObjectWithData(responseData,
                                                           options: NSJSONReadingOptions.AllowFragments)
                print(json)

                if let dict = json as? Dictionary<String, AnyObject>
                {
                    self.ModelFromJSON = dict
                }

            } catch {
                print("Could not serial data")
            }
        }
    }

}

感谢您对此事的任何帮助!

0 个答案:

没有答案