如何在swift iOS中进行nsurlsession,如何为REST API创建全局功能?

时间:2016-06-24 09:25:26

标签: ios swift rest nsurlsession

如何通过NSURLSESSION创建一个函数来调用RESTful api,这个函数可以在swift iOS中的每个控制器上使用,即在app中随处可见的singleton对象 这是我提出的代码。但是一旦我调用该方法,它就会崩溃,直到return语句,jsonresponse为空。

func apicall (mainurl : String, method :String,params :String ) -> NSDictionary{

    var jsonresponse = NSDictionary()
    let url:NSURL = NSURL(string: mainurl)!
    let session = NSURLSession.sharedSession()

    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = method
    //        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

    let paramString = params
    request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)

    let task = session.dataTaskWithRequest(request) {
        (
        let data, let response, let error) in
        enum JSONError: String, ErrorType {
            case NoData = "ERROR: no data"
            case ConversionFailed = "ERROR: conversion from JSON failed"
        }
        do{
            guard let _:NSData = data, let _:NSURLResponse = response  where error == nil else {
                print("error")
                throw JSONError.NoData
            }
            print("data = \(data), response = \(response) , error = \(error)")


            guard let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary else {
                throw JSONError.ConversionFailed
            }
            jsonresponse = json

        }
        catch let error as JSONError {
            print(error.rawValue)
        } catch let error as NSError {
            print(error.debugDescription)
        }
    }
    task.resume()

    return jsonresponse
}

}

1 个答案:

答案 0 :(得分:0)

NSUrlSession Reference

1.Shared seesion返回单个对象的默认会话。如果你想使用自己的会话,那么创建一个返回会话单例的方法。

func restAPICall(requestUrl:NSURL, httpMethod:String, params:NSDictionary)
        {
            let session = NSURLSession.sharedSession()
            var dataTask: NSURLSessionDataTask;
            do
            {
                let httpData = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
                let request = NSMutableURLRequest.init(URL: requestUrl)
                request.addValue("application/json", forHTTPHeaderField: "Content-Type");
                request.HTTPBody = httpData
                request.HTTPMethod = "POST"

                dataTask = session.dataTaskWithRequest(request){(data, response, error) in

                    do
                    {
                        let jsonData = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves)
                        print("\(ViewController.count)----------\n" + jsonData.description + "\n--------------\n");
                        ViewController.count = ViewController.count + 1

                    }
                    catch
                    {
                        print(error)
                    }
                }


                dataTask.resume();
            }
            catch
            {
                print(error)
            }
        }