如何在Swift 2中从全局函数中设置参数

时间:2022-03-26 08:26:06

I am trying to create HTTP request with Swift2 and to return response outside of nested function. My code looks like this:

我正在尝试使用Swift2创建HTTP请求并返回嵌套函数之外的响应。我的代码是这样的:

let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
   if (error != nil) {
       print(error)
   } else {
       let httpResponse = response as? NSHTTPURLResponse
       print(httpResponse)
       print(data)
       // return data
   }

I would like to return data variable outside of nested function. Or to have some other variable defined before nested function, which I can set inside of nested function. Like this:

我想返回嵌套函数之外的数据变量。或者在嵌套函数之前定义其他变量,我可以在嵌套函数中设置。是这样的:

var test = "";
// some nested function
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
    test = "test"
})

Anybody has some suggestion for this problem?

有人对这个问题有什么建议吗?

1 个解决方案

#1


2  

If you want to synchronously wait until the data task has finished so that you can return the fetched data, you have to use a semaphore.

如果您想要同步地等待直到数据任务完成,以便您可以返回获取的数据,那么您必须使用一个信号量。

func getDataSynchronously(request: NSURLRequest) -> NSData? {
    var returnData: NSData?
    let semaphore = dispatch_semaphore_create(0)
    let dataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) in
        returnData = data
        dispatch_semaphore_signal(semaphore)
    })
    dataTask.resume()
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
    return returnData
}

The semaphore will force the calling thread to stop and wait until it is signaled upon completion of the data task. Calling the above function would look like this

信号量将强制调用线程停止并等待,直到数据任务完成时发出信号。调用上面的函数就像这样。

let request = NSURLRequest(URL: NSURL(string: "https://www.google.com")!)
let data = getDataSynchronously(request)
print("Synchronously fetched \(data!.length) bytes")

On the other hand, if you want to kick-off the data task in the background and be asynchronously notified about its completion, you can add your own completion block to the function's signature.

另一方面,如果您希望在后台启动数据任务并异步通知其完成,您可以将自己的完成块添加到函数的签名中。

func getDataAsynchronously(request: NSURLRequest, completion: NSData? -> ()) {
    let dataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) in
        completion(data)
    })
    dataTask.resume()
}

Calling the asynchronous method could look like this

调用异步方法可以如下所示

let request = NSURLRequest(URL: NSURL(string: "https://www.google.com")!)
getDataAsynchronously(request) { data in
    print("Asynchronously fetched \(data!.length) bytes")
}

#1


2  

If you want to synchronously wait until the data task has finished so that you can return the fetched data, you have to use a semaphore.

如果您想要同步地等待直到数据任务完成,以便您可以返回获取的数据,那么您必须使用一个信号量。

func getDataSynchronously(request: NSURLRequest) -> NSData? {
    var returnData: NSData?
    let semaphore = dispatch_semaphore_create(0)
    let dataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) in
        returnData = data
        dispatch_semaphore_signal(semaphore)
    })
    dataTask.resume()
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
    return returnData
}

The semaphore will force the calling thread to stop and wait until it is signaled upon completion of the data task. Calling the above function would look like this

信号量将强制调用线程停止并等待,直到数据任务完成时发出信号。调用上面的函数就像这样。

let request = NSURLRequest(URL: NSURL(string: "https://www.google.com")!)
let data = getDataSynchronously(request)
print("Synchronously fetched \(data!.length) bytes")

On the other hand, if you want to kick-off the data task in the background and be asynchronously notified about its completion, you can add your own completion block to the function's signature.

另一方面,如果您希望在后台启动数据任务并异步通知其完成,您可以将自己的完成块添加到函数的签名中。

func getDataAsynchronously(request: NSURLRequest, completion: NSData? -> ()) {
    let dataTask = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data, response, error) in
        completion(data)
    })
    dataTask.resume()
}

Calling the asynchronous method could look like this

调用异步方法可以如下所示

let request = NSURLRequest(URL: NSURL(string: "https://www.google.com")!)
getDataAsynchronously(request) { data in
    print("Asynchronously fetched \(data!.length) bytes")
}