如何从xmlArray显示我的图像?

时间:2016-06-30 06:11:11

标签: xml swift

enter image description here enter image description here我有这个函数,这是一个xml文件,我想将图片网址保存在数组中并显示在UIImageView,但该怎么做?我是以错误的方式做的吗?

func latestNews(){

    Alamofire.request(.POST, "https://api.jocom.com.my/feed", parameters: ["req" : "news"])

        .responseData { response in

            print(response.request)  // original URL request

            print(response.result)   // result of response serialization

            let xmlLatestNews = SWXMLHash.parse(response.data!)
            print(xmlLatestNews)


            for elem in xmlLatestNews["rss"]["channel"]["item"]{

                let latestNewsImg: UIImageView = UIImageView(frame: CGRectMake(0.0, 0.0, 100, self.latestNewsScrollView.frame.size.height))
                latestNewsImg.backgroundColor = UIColor.redColor()


                let thumbnailURL = NSURL(string: (elem["thumbnail"].element!.text!))

               //self.xmlArray is a NSURL array  (var xmlArray = [NSURL]())

                self.xmlArray.append(thumbnailURL!)


                self.latestNewsScrollView.addSubview(latestNewsImg)
            }


           print(self.xmlArray)

    }
}

1 个答案:

答案 0 :(得分:0)

如果从服务器返回的项目很多,我通常会创建一个模型对象来存储这些属性。在你的情况下,如果它只是URL。我会将它存储为String数组。

>Open Android Studio.
>Open Your Project.
>Click on Gradle (From Right Side Panel, you will see Gradle Bar)
>Click on Refresh (Click on Refresh from Gradle Bar , you will see List
 Gradle scripts of your Project)
>Click on Your Project (Your Project Name form List(root))
>Click on Tasks
>Click on android
>Double Click on signingReport (You will get SHA1 and MD5 in Run Bar)

然后只需找回字符串并显示图像

var stringURLArray = [String]()
stringURLArray.append(elem["thumbnail"].element!.text)

作为示例分配给特定图像。

let stringURL = stringURLArray[indexPath.row] as? String
let url = NSURL(string: stringURL)
let data = NSData(contentsOfURL: url!)
cell.yourImage.image = UIImage(data: data!)

创建循环并以编程方式添加图像:

    let imageView1 = UIImageView(frame: CGRectMake(0, 0, 200, 50))
    let stringURL = stringURLArray[0] // you can choose which index you want
    let url = NSURL(string: stringURL)
    let data = NSData(contentsOfURL: url!)
    imageView1.image = UIImage(data: data!)
    self.view.addSubview(imageView1)