图像无法加载Swift

时间:2016-05-30 11:23:27

标签: ios swift image controller load

我在尝试将图像从控制器加载到另一个控制器时遇到问题。问题是,当尝试加载新的Controller时,运行同一类的2次。

ViewController中的代码

   func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)

        let row = ids[indexPath.row]
        let next = self.storyboard?.instantiateViewControllerWithIdentifier("NewsController") as! NewsController
        next.id = row
        self.presentViewController(next, animated: true, completion: nil)

        }

NewsController中的代码:

  func tableView(tableView:   UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
            // Retrieve cell

            let cellIdentifier: String = "NewCell"
            let myCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as!NewDetailCell

            // Get the location to be shown
            let item: LocationModel = feedItems[indexPath.row] as! LocationModel


            myCell.titLabel!.text  =   item.titulo
            myCell.subLabel!.text   =  item.subtitulo
            myCell.cuerpoLabel!.text = item.cuerpo
            var urlimg : String = item.imgNot!

            if urlimg == ""{
                urlimg = "abc.jpg"
            }
            var image = UIImageView()

            image = loadImageFromUrl("MyURL" + urlimg, view: myCell.newImage!)!
myCell.newImage = image
    .
    .
    .

loadImageFromUrl():

func loadImageFromUrl(url: String!, view: UIImageView!) -> UIImageView?{

        // Create Url from string
        let url = NSURL(string: url)!

        // Download task:
        // - sharedSession = global NSURLCache, NSHTTPCookieStorage and NSURLCredentialStorage objects.
        let task = NSURLSession.sharedSession().dataTaskWithURL(url) { (responseData, responseUrl, error) -> Void in
            // if responseData is not null...
            if let data = responseData{

                // execute in UI thread
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    view.image = UIImage(data: data)
                })

            }
        }

        // Run task
        task.resume()
        return UIImageView (image : view.image)
    }

谢谢!

1 个答案:

答案 0 :(得分:0)

您应该检查您在loadImageFromUrl中传递的URL字符串。 另外我认为最好只将URlString作为参数获取并返回completionBlockWith UIImage?