使用 NSURLSession 和闭包加载数据 iOS

Load data with NSURLSession and closure iOS

我使用这个函数来获取图像的 link 但我只有初始化中的变量。

func getLinkImage(link_news: String, separator: String) -> String {
    let url = NSURL(string: link_news)
    var link_image_news = "http://www.website.com"
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) { (data, response, error) -> Void in
        if error == nil {
            let urlContent = NSString(data: data!, encoding: NSUTF8StringEncoding)
            //print(urlContent)
            let urlContentArray = urlContent?.componentsSeparatedByString(separator)
            // search link's image
                print("----------Link's Image----------")
                var image_news = urlContentArray?[1].componentsSeparatedByString("<img alt=")
                image_news = image_news?[1].componentsSeparatedByString("src=")
                image_news = image_news?[1].componentsSeparatedByString("\"")
                link_image_news = "http://www.website.com" + image_news![1]
                print("the link of image is : "+link_image_news)
            // end of search link's image
        }
        else {
            print("Error in the Image News load from Website")
            print(url!)
        }
    }
    task.resume()
    return link_image_news
}

当我调用该函数时,我只有初始化值 (link_image_news = http://www.website.com),许多秒后我得到了正确值的打印(图像的 link ).

我认为这是服务器响应时间的问题。我该如何解决这个问题? 我发现了一些带有闭包(完成)的东西,但我真的不明白它是如何工作的,我是 Swift

中的新手

这是交易:

NSURLSession“任务”获取一段代码,一旦服务器的响应被完全接收到,它就会调用该代码块。

当您调用 task.resume() 时,会立即调用 return,甚至在 iOS 开始向远程服务器发送请求之前。您需要做的是重写您的 getLinkImage 函数,使其不是 return 值,并将完成块作为参数。

使该完成块以字符串作为参数。让您的 getLinkImage 函数从数据任务的完成块内部调用完成块,包装在 dispatch_async 中,在主线程上调用完成块。

编辑:

您修改后的 getLinkImage 方法可能如下所示:

func getLinkImage(
  link_news: String, 
  separator: String,
  completion: (ok: Bool, resultString: String?) -> ()
  )
{
    let url = NSURL(string: link_news)
    var link_image_news = "http://www.website.com"
    let task = NSURLSession.sharedSession().dataTaskWithURL(url!) 
    {
     (data, response, error) -> Void in
        if error == nil {
            let urlContent = NSString(data: data!, 
              encoding: NSUTF8StringEncoding)
            //print(urlContent)
            let urlContentArray = 
              urlContent?.componentsSeparatedByString(separator)
            // search link's image
                print("----------Link's Image----------")
                var image_news = 
                  urlContentArray?[1].componentsSeparatedByString("<img alt=")
                image_news = image_news?[1].componentsSeparatedByString("src=")
                image_news = image_news?[1].componentsSeparatedByString("\"")
                link_image_news = "http://www.website.com" + image_news![1]
                print("the link of image is : "+link_image_news)
            // end of search link's image
            dispatch_async(dispatch_get_main_queue())
            {
              //We now have the string, so pass it to the completion block
              completion(true, link_image_news); 
            {
        }
        else {
            print("Error in the Image News load from Website")
            print(url!)
            dispatch_async(dispatch_get_main_queue())
            {
              //There was an error, so pass nil to completion
              completion(false, nil); 
            {
    }
    task.resume()
}