同步从方法返回REST调用的响应

时间:2016-04-18 08:29:37

标签: ios swift rest promise ios9

我创建了一个执行REST调用并返回HTTP响应代码的方法:

import Foundation

class RestUtil{

enum HTTPMethod: String{
        case GET, POST, PUT
    }

    static func sendREST(url: String, data: String, httpMethod: HTTPMethod) -> String{

        let request = NSMutableURLRequest(URL: NSURL(string: url)!)
        let dataEncoded = data.dataUsingEncoding(NSUTF8StringEncoding)

        request.HTTPMethod = httpMethod.rawValue
        request.HTTPBody = dataEncoded

        print("HTTPMethod: " + httpMethod.rawValue)

        var statusCode : Int = 0
        let startTime : Double = NSDate().timeIntervalSince1970

        func completionFunc(data: NSData?, response: NSURLResponse?, error: NSError?){
            let httpResponse = response as! NSHTTPURLResponse
            statusCode = httpResponse.statusCode
            print("statusCode: " + String(statusCode))
            print(error)
        };

        let task = NSURLSession.sharedSession().uploadTaskWithRequest(request,
                                                                      fromData: dataEncoded!,completionHandler: completionFunc)


        task.resume()
        var currentTime : Double = NSDate().timeIntervalSince1970
        var elapsedTime : Double = (currentTime - startTime)
        let timeOut : Double = 10

        while(statusCode == 0 && elapsedTime < timeOut){
            sleep(1);
            currentTime = NSDate().timeIntervalSince1970
            elapsedTime = (currentTime - startTime)
        }

        print("Final elapsedTime: " + String(elapsedTime))

        return String(statusCode)
    }

}

该方法执行REST调用并从服务器返回HTTP状态代码。该方法的目的是让调用方法在完成后从REST调用中获取返回代码,而不必提供用于处理响应状态代码的回调函数,即该方法应该是同步的(就像现在一样) )。

它有效,但是如果响应还没有,那么循环检查会感觉有点笨拙。为此方法实现正确promise-like功能的最简单方法是什么(以便在可用时立即返回返回代码),最好不使用外部库?这是不可能的,例如使用NSOperationQueue

0 个答案:

没有答案