通过Swift命令行程序使用NSURLSession [英] Using NSURLSession from a Swift command line program

查看:123
本文介绍了通过Swift命令行程序使用NSURLSession的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试先测试一个概念验证的命令行应用程序,然后再将其集成到更大的应用程序中.我想做的是使用NSURLSession使用此示例下载一些数据.但是,如果我使用一个简单的OS X命令行应用程序中给出的示例,则该应用程序将在检索数据之前退出.

I'm trying to test a little proof-of-concept command line app prior to integrating it into a larger app. What I'm trying to do is download some data using NSURLSession using this example. However it appears that if I use the examples given in a simple OS X command line app then the app exits prior to the data being retrieved.

如何使用NSURLSession从独立的命令行应用程序下载数据?我所读的是使用 NSRunLoop 但是,我还没有在Swift中找到一个清晰的示例,因此,如果NSRunLoop实际上是可行的方法,那么任何示例都将不胜感激.

How can I download data from a stand-alone command line app using NSURLSession? What I've read about is using NSRunLoop however I've not yet found a clear example in Swift so if NSRunLoop is actually the way to go then any examples would be appreciated.

也欢迎使用其他其他任何方法从Swift命令行应用程序的URL下载数据(无限while循环吗?).

Any other strategies for downloading data from a URL for a Swift command line app is also welcome (infinite while loop?).

推荐答案

您可以使用信号量来阻止当前线程,并等待URL会话结束.

You can use a semaphore to block the current thread and wait for your URL session to finish.

创建信号灯,启动您的URL会话,然后等待信号灯.从您的URL会话完成回调中,发出信号量.

Create the semaphore, kick off your URL session, then wait on the semaphore. From your URL session completion callback, signal the semaphore.

您可以使用全局标志(声明一个易失的布尔变量)并从while循环中轮询它,但这并不是最佳选择.一方面,您不必要地消耗CPU周期.

You could use a global flag (declare a volatile boolean variable) and poll that from a while loop, but that is less optimal. For one thing, you're burning CPU cycles unnecessarily.

这是我在操场上做的一个简单例子:

Here's a quick example I did using a playground:

import Foundation

var sema = DispatchSemaphore( value: 0 )

class Delegate : NSObject, URLSessionDataDelegate
{
    func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)
    {
        print("got data \(String(data: data, encoding: .utf8 ) ?? "<empty>")");
        sema.signal()
    }
}

let config = URLSessionConfiguration.default
let session = URLSession(configuration: config, delegate: Delegate(), delegateQueue: nil )

guard let url = URL( string:"http://apple.com" ) else { fatalError("Could not create URL object") }

session.dataTask( with: url ).resume()    

sema.wait()

这篇关于通过Swift命令行程序使用NSURLSession的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆