2015-04-02 72 views
1

我想在图像下载完成后设置图像变量。我正在使用'inout'将图像变量传递给我的下载函数,但它没有设置。Swift inout没有设置

这里是我的代码:

var img: UIImage? 

func downloadImage(url: String?, inout image: UIImage?) { 

    if url != nil { 

     var imgURL: NSURL = NSURL(string: url!)! 
     var request: NSURLRequest = NSURLRequest(URL: imgURL) 

     NSURLConnection.sendAsynchronousRequest(request, queue: 
      NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!, 
      data: NSData!,error: NSError!) -> Void in 

      if error == nil { 
       dispatch_async(dispatch_get_main_queue(), { 

        // setting img via inout doesn't work 
        image = UIImage(data: data) // inout img should be set but its not 
        println(img) 

        // setting img directly works, but don't want it hard coded 
        img = UIImage(data: data) 
        println(img) 

       }) 
      } 
      else { 
       println("Error") 
      } 
     }) 
    } 
} 

downloadImage(<<IMAGE URL HERE>>, &img) // passing img as an inout 

林期待变量img这是作为一个INOUT的图像被下载后,设置的downloadImage功能过去了,但它永远不会被更新。

我期待行:image = UIImage(data: data)来更新IMG INOUT变量,但它没有。

但是,直接引用img变量的行:img = UIImage(data: data)被更新。

但我不想直接在函数中硬编码img变量,我希望能够通过inout传递任何我想要的变量。

任何想法,为什么我不能更新inout变量,以及如何解决它。 谢谢。

+1

异步代码不会同步运行。 – nhgrif 2015-04-02 01:09:08

+0

你的评论是不是很有帮助 - 一些意见,将不胜感激 – Bingo 2015-04-02 01:12:53

+0

您的功能运行异步代码。异步块中的代码在函数返回之前不会完成。除了期望在函数返回之前完成异步代码之外,代码没有任何问题。 – nhgrif 2015-04-02 01:13:36

回答

2

您需要将“延续”传递给您的downloadImage()函数;延续是做什么用下载的图像:像这样:

func downloadImage(url: String?, cont: ((UIImage?) -> Void)?) { 
    if url != nil { 

    var imgURL: NSURL = NSURL(string: url!)! 
    var request: NSURLRequest = NSURLRequest(URL: imgURL) 

    NSURLConnection.sendAsynchronousRequest (request, 
     queue:NSOperationQueue.mainQueue(), 
     completionHandler: { 
      (response: NSURLResponse!, data: NSData!,error: NSError!) -> Void in 
      if error == nil { 
      dispatch_async(dispatch_get_main_queue(), { 
       // No point making an image unless the 'cont' exists 
       cont?(UIImage(data: data)) 
       return 
      }) 
      } 
      else { println ("Error") } 
     }) 
    } 
} 

,然后你使用这样的:

var theImage : UIImage? 

downloadImage ("https://imgur.com/Y6yQQGY") { (image:UIImage?) in 
    theImage = image 
} 

在那里我已经利用语法尾随关闭和简单地分配可选,下载的图像到所需的变量。

另外,请注意,我没有检查过你的线程结构;它可能是cont函数应该在其他一些队列上调用 - 但是,你会得到延续的传递点。

+0

谢谢。我不确定这个解决方案是否有效,它会使操场崩溃。你能运行它吗? – Bingo 2015-04-02 02:26:51

+0

我得到一个编译器错误的dispatch_async行:不能用类型'(dispatch_queue_t!,() - () - > $ T3)'参数列表调用'init''...任何想法如何解决这个问题? – Bingo 2015-04-02 02:33:08

+0

在'cont?()'行后面添加'return'。类型推理器已经决定'cont?()'可能会返回一些不应该的东西。 – GoZoner 2015-04-02 02:34:33