无法从网络向 iCarousel 显示图像 url

Can't Show images to iCarousel from web url

我想在 iCarousel SlideShow 上显示网站上的一些图片。

我从 iCarousel 获得空幻灯片。

我是初学者,偶然在我的应用程序上尝试了很多代码,但注意到发生了

这是我的完整代码:

import UIKit

class ViewController: UIViewController , iCarouselDataSource, iCarouselDelegate {

    @IBOutlet weak var imageView: UIImageView!

    @IBOutlet weak var allimages: UIImageView!

    internal var urll:NSURL!

    @IBOutlet weak var carouselView: iCarousel!

    var numbers = [Int]()
    var urls = [String]()


    func carousel(carousel: iCarousel, viewForItemAtIndex index: Int, reusingView view: UIView?) -> UIView {
        let tempView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))

        let images = UIButton(frame: CGRect(x: 0, y: 0, width: 300, height: 200))
        images.backgroundColor = UIColor.blueColor()
        images.backgroundImageForState(.Normal)
        images.backgroundRectForBounds(CGRect(x: 0, y: 0, width: 300, height: 200))
        tempView.addSubview(images)

        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
        imageView.backgroundColor = UIColor.orangeColor()


        for item in self.urls {
            print (item)

            let s = item
            let url = NSURL(string: s)
            let session = NSURLSession.sharedSession()
            let task = session.downloadTaskWithURL(url!)
            {
                (url: NSURL?, res: NSURLResponse?, e: NSError?) in
                let d = NSData(contentsOfURL: url!)
                let image = UIImage(data: d!)

                dispatch_async(dispatch_get_main_queue()) {
                    imageView.image = image
                }
            }
            task.resume()
        }

    return images

    }




    func carousel(carousel: iCarousel, valueForOption option: iCarouselOption, withDefault value: CGFloat) -> CGFloat {
        if option ==  iCarouselOption.Spacing {
            return value * 1.1
        }
        return value
    }

    override func awakeFromNib() {
        super.awakeFromNib()
         numbers = [1,2,3,4]
    }

    func numberOfItemsInCarousel(carousel: iCarousel) -> Int {
        return numbers.count
    }

    //==============================================================
    override func viewDidLoad() {






        carouselView.type = .Rotary
        carouselView.autoscroll = 0.4
//        let defaults = NSUserDefaults.standardUserDefaults()



        urll = NSURL(string: "http://xxxxxxxxx.com/api/?slider=uij6sdnb")

        let session = NSURLSession.sharedSession()
        let task = session.dataTaskWithURL(urll) {(NSData, response, error) -> Void in
            do {
                let records = try NSJSONSerialization.JSONObjectWithData(NSData!, options: NSJSONReadingOptions.MutableContainers) as! NSArray


                for record in records {
                    let urlid = Int(record["slide_id"] as! String)
                    let urimage = record["slide_url"] as! String


             print(urlid)
                    print(urimage)
                    self.urls = [urimage]
//                    print(self.urls.count)
                                }
            }
            catch {
                print("Json Error")

            }
        }


        task.resume()

任何帮助将不胜感激。

这是我的完整代码。

但是正如您看到的那样,它是 4 幅图像。

对于更多或更少的图像,您可以轻松应用更改。

我添加了来自 jared Davinson Youtube 频道的 icrousel。

尽情享受吧。

 //
//  ViewController.swift
//  parniapharmed
//
//  Created by Alfredo Uzumaki on 2016 AP.
//  Copyright © 2016 AP Alfredo Uzumaki. All rights reserved.
//

import UIKit
import SystemConfiguration // for checking internet connection


class ViewController: UIViewController {  // if you had any problem. command this line and uncommand the below line !

//    class ViewController: UIViewController , iCarouselDataSource, iCarouselDelegate {



@IBOutlet weak var allimages: UIImageView!

internal var urll:NSURL!

@IBOutlet weak var carouselView: iCarousel!

@IBOutlet weak var img1: UIImageView!
@IBOutlet weak var img2: UIImageView!
@IBOutlet weak var img3: UIImageView!
@IBOutlet weak var img4: UIImageView!

@IBOutlet weak var allimagetop: UIView!

internal var imageNinja:String = ""

internal var hasInternet:Bool! // for checking internet connection

var numbers = [Int]()
var urls = [String]()

internal var urimage = [String]()

internal var image1:String = ""
internal var image2:String = ""
internal var image3:String = ""
internal var image4:String = ""

internal var imageArray: [UIImage] = []


func carousel(carousel: iCarousel, viewForItemAtIndex index: Int, reusingView view: UIView?) -> UIView {

    var tempView = UIView(frame: CGRect(x: 0, y: 0, width: 300, height: 200))

    let images = UIButton(frame: CGRect(x: 0, y: 0, width: 300, height: 200))

    images.backgroundColor = UIColor.blueColor()
    images.backgroundImageForState(.Normal)
    images.backgroundRectForBounds(CGRect(x: 0, y: 0, width: 300, height: 200))

    tempView.addSubview(images)

    let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 400, height: 200))
    imageView.image = UIImage(named: "loading")

    if (imageNinja != "") && (imageArray.count == 4) {  // Checking if images fully loaded you can Delete Seccond Condition if it Coused any Error

    imageView.backgroundColor = UIColor.orangeColor()
    imageView.image = imageArray[index]
    tempView.addSubview(imageView)
    }
    return imageView
}


func carousel(carousel: iCarousel, valueForOption option: iCarouselOption, withDefault value: CGFloat) -> CGFloat {
    if option ==  iCarouselOption.Spacing {
        return value * 1.1
    }
    return value
}

override func awakeFromNib() {
    super.awakeFromNib()
    numbers = [1,2,3,4] // i wrote it manualy but you can change it to: numbers = imageArray.count  or write the th numbers of your images.
}

func numberOfItemsInCarousel(carousel: iCarousel) -> Int {
    return numbers.count
}





//===========================Begin of View Did Load===================================


override func viewDidLoad() {

    carouselView.type = .Rotary
    carouselView.autoscroll = 0.1

    hasInternet = connectedToNetwork() //checking internet again !
    print(hasInternet) // if true then internet is ok

    if hasInternet == true {
    urll = NSURL(string: "http://yourwebsite.com/api/?slider=uij6sdnb") // <== put your php address here !!
    let session = NSURLSession.sharedSession()
    let task = session.dataTaskWithURL(urll) {(data, response, error) -> Void in
        do {
            let records = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as! NSArray
            for record in records {
                //slide_url is the subject of database row from php... change it to yours
                let urimage = record["slide_url"] as! String
                self.urls.append(urimage)
            }
            print(self.urls[2])
            self.image1 = self.urls[0]
            self.image2 = self.urls[1]
            self.image3 = self.urls[2]
            self.image4 = self.urls[3]
        }
        catch {
            print("Json Error")
        }

        while self.imageNinja == "" {
            self.image1 = self.urls[0]
            self.image2 = self.urls[1]
            self.image3 = self.urls[2]
            self.image4 = self.urls[3]
            print("4th image downloaded")
            print(self.image4)

           //----------------------------------- downoad image -----------------------------------------
            let url = NSURL(string: self.image1)
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
                let data = NSData(contentsOfURL: url!) //make sure your image in this url does exist, otherwise unwrap in a if let check
                dispatch_async(dispatch_get_main_queue(), {
                    let image = UIImage(data: data!)
                    self.imageArray.append(image!)
                });
            }
            //----------------------------------- downoad image -----------------------------------------
            //----------------------------------- downoad image -----------------------------------------
            let url2 = NSURL(string: self.image2)
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
                let data = NSData(contentsOfURL: url2!) //make sure your image in this url does exist, otherwise unwrap in a if let check
                dispatch_async(dispatch_get_main_queue(), {
                    let image = UIImage(data: data!)
                    self.imageArray.append(image!)
                });
            }
            //----------------------------------- downoad image -----------------------------------------
            //----------------------------------- downoad image -----------------------------------------
            let url3 = NSURL(string: self.image3)
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
                let data = NSData(contentsOfURL: url3!) //make sure your image in this url does exist, otherwise unwrap in a if let check
                dispatch_async(dispatch_get_main_queue(), {
                    let image = UIImage(data: data!)
                    self.imageArray.append(image!)
                });
            }
            //----------------------------------- downoad image -----------------------------------------
            //----------------------------------- downoad image -----------------------------------------
            let url4 = NSURL(string: self.image4)
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
                let data = NSData(contentsOfURL: url4!) //make sure your image in this url does exist, otherwise unwrap in a if let check
                dispatch_async(dispatch_get_main_queue(), {
                    let image = UIImage(data: data!)
                    self.imageArray.append(image!)



                    print("imageArray Count is is :")
                    print(self.imageArray.count)
                    self.carouselView.reloadData()  //this one is do nothing! i put it for luck!
                });
            }
            //----------------------------------- downoad image -----------------------------------------

            self.imageNinja = "hhh"

        }

    }

    task.resume()

    }


    // ================================= end of view did load

}

// checking internet connection
func connectedToNetwork() -> Bool {
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)
    guard let defaultRouteReachability = withUnsafePointer(&zeroAddress, {
        SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer([=10=]))
    }) else {
        return false
    }
    var flags : SCNetworkReachabilityFlags = []

    if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == false {
        return false
    }
    let isReachable = flags.contains(.Reachable)
    let needsConnection = flags.contains(.ConnectionRequired)
    return (isReachable && !needsConnection)
}

}