Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios Swift-使用API中的数据填充UITableView_Ios_Swift_Uitableview_Api_Data Retrieval - Fatal编程技术网

Ios Swift-使用API中的数据填充UITableView

Ios Swift-使用API中的数据填充UITableView,ios,swift,uitableview,api,data-retrieval,Ios,Swift,Uitableview,Api,Data Retrieval,我正在尝试使用UITableView设置一个提要页面,从Node.js API检索所有JSON数据 看起来它正在工作,但速度非常慢,有时无法检索所有图像。有没有办法让它完全工作,并优化代码 import UIKit class homeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! v

我正在尝试使用UITableView设置一个提要页面,从Node.js API检索所有JSON数据

看起来它正在工作,但速度非常慢,有时无法检索所有图像。有没有办法让它完全工作,并优化代码

import UIKit




class homeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {



@IBOutlet weak var tableView: UITableView!


var jsonData : [NSDictionary] = [NSDictionary]()
var imageUrls: NSDictionary = NSDictionary()
var urlsArray: [NSURL]! = [NSURL]()


override func viewDidLoad() {
    super.viewDidLoad()

    self.tableView.reloadData()

    let qualityOfServiceClass = QOS_CLASS_BACKGROUND
    let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)
    dispatch_async(backgroundQueue, {
        println("This is run on the background queue")
        self.refreshData()
        self.getImage()

        dispatch_async(dispatch_get_main_queue(), { () -> Void in
            println("This is run on the main queue, after the previous code in outer block")
            self.tableView.reloadData()
        })
    })




}

override func viewWillAppear(animated: Bool) {



}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}





func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


   return jsonData.count



}



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


    var type = jsonData[indexPath.row]["type"] as! Int

    if type == 1 {


        println("Type= \(type)")

        let cell1 : cellTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as! cellTableViewCell


        //If images url are retrieved, load them. Otherwise, load the placeholders
        if self.urlsArray.isEmpty == false {

            println("Tiè: \(self.urlsArray[indexPath.row])")


            if let data = NSData(contentsOfURL: self.urlsArray[indexPath.row]) {

                    cell1.profileImg?.image = UIImage(data: data)

                }

        } else {

            cell1.profileImg?.image = UIImage(named: "placeholder.png")

        }


        cell1.testLbl.text = (self.jsonData[indexPath.row]["author"] as? String)!

        return cell1

    } else {


        let cell2 : cell2TableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell2") as! cell2TableViewCell


        return cell2
    }
}


func refreshData()   {


    let requestURL = NSURL(string:"http://adall.ga/api/feeds/author/mat/0")!


    var request = NSMutableURLRequest(URL: requestURL)
    request.HTTPMethod = "GET"



    request.addValue(userToken, forHTTPHeaderField: "tb-token")

    let session = NSURLSession.sharedSession()

    let task = session.dataTaskWithRequest(request) {
        data, response, error in


        println(response)

        var dataString = NSString(data: data, encoding: NSUTF8StringEncoding)

        println(dataString)

        //let jsonResult : NSDictionary = (NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: nil) as? NSDictionary)!
        //jsonData = (NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers , error: nil) as? NSArray)!


        self.jsonData = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as! [NSDictionary]



    }

    task.resume()

    var index: Int
    for index = 0; index < 10000; ++index {
        print("Index: \(index), Task state: \(task.state)")
    }
}



func getImage() {

    var i = 0

    for jsonSingleData in jsonData {

        let author = jsonSingleData["author"] as! String


        let requestURL2 = NSURL(string: "http://adall.ga/api/users/" + author + "/image")!

        println("request: \(requestURL2)")


        var request2 = NSMutableURLRequest(URL: requestURL2)
        request2.HTTPMethod = "GET"


        request2.addValue(userToken!, forHTTPHeaderField: "tb-token")


        let session2 = NSURLSession.sharedSession()

        let task2 = session2.dataTaskWithRequest(request2) {
            data, response, error in


            println("response= \(response)")


            var dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
            println(dataString)



            self.imageUrls = (NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary)


            //check if exists
            let imageUrl = self.imageUrls["url"] as! String

            let url = NSURL(string: "http://" +  imageUrl)

            self.urlsArray.append(url!)

            println(self.urlsArray)


            }

        task2.resume()


    }
}
导入UIKit
类homeViewController:UIViewController、UITableViewDelegate、UITableViewDataSource{
@IBVAR表格视图:UITableView!
var jsonData:[NSDictionary]=[NSDictionary]()
var imageUrls:NSDictionary=NSDictionary()
变量urlsArray:[NSURL]!=[NSURL]()
重写func viewDidLoad(){
super.viewDidLoad()
self.tableView.reloadData()
让qualityOfServiceClass=QOS\u类\u后台
let backgroundQueue=dispatch\u get\u global\u队列(qualityOfServiceClass,0)
调度异步(后台队列{
println(“这在后台队列上运行”)
self.refreshData()
self.getImage()
dispatch\u async(dispatch\u get\u main\u queue(),{()->Void in
println(“这在主队列上运行,在外部块中的前一个代码之后”)
self.tableView.reloadData()
})
})
}
覆盖功能视图将出现(动画:Bool){
}
重写函数didReceiveMemoryWarning(){
超级。我收到了记忆警告()
//处置所有可以重新创建的资源。
}
func tableView(tableView:UITableView,numberofrowsinssection:Int)->Int{
返回jsonData.count
}
func tableView(tableView:UITableView,cellForRowAtIndexPath:nsindepath)->UITableView单元格{
var type=jsonData[indexPath.row][“type”]as!Int
如果类型==1{
println(“类型=\(类型)”)
将cell1:cellTableViewCell=self.tableView.dequeueReusableCellWithIdentifier(“cell”)设为!cellTableViewCell
//如果检索到图像url,请加载它们。否则,请加载占位符
如果self.urlsArray.isEmpty==false{
println(“Tiè:\(self.urlsArray[indexPath.row]))
如果let data=NSData(contentsOfURL:self.urlsArray[indepath.row]){
cell1.profileImg?.image=UIImage(数据:数据)
}
}否则{
cell1.profileImg?.image=UIImage(名为:“placeholder.png”)
}
cell1.testLbl.text=(self.jsonData[indexPath.row][“author”]as?String)!
返回单元格1
}否则{
将cell2:cell2TableViewCell=self.tableView.dequeueReusableCellWithIdentifier(“cell2”)设为!cell2TableViewCell
返回单元格2
}
}
func refreshData(){
让requestURL=NSURL(字符串:http://adall.ga/api/feeds/author/mat/0")!
var request=NSMutableURLRequest(URL:requestURL)
request.HTTPMethod=“GET”
request.addValue(userToken,forHTTPHeaderField:“tb token”)
let session=NSURLSession.sharedSession()
让task=session.dataTaskWithRequest(请求){
数据、响应、错误
println(响应)
var dataString=NSString(数据:数据,编码:NSUTF8StringEncoding)
println(数据字符串)
//让jsonResult:NSDictionary=(NSJSONSerialization.JSONObjectWithData(data!,选项:NSJSONReadingOptions.MutableContainers,错误:nil)作为?NSDictionary)!
//jsonData=(NSJSONSerialization.JSONObjectWithData(data!,选项:NSJSONReadingOptions.MutableContainers,错误:nil)as?NSArray)!
self.jsonData=NSJSONSerialization.JSONObjectWithData(数据,选项:NSJSONReadingOptions.AllowFragments,错误:nil)为![NSDictionary]
}
task.resume()
var指数:Int
对于索引=0;索引<10000;++索引{
打印(“索引:\(索引),任务状态:\(任务状态)”)
}
}
func getImage(){
变量i=0
对于jsonData中的jsonSingleData{
让author=jsonSingleData[“author”]作为!字符串
让requestURL2=NSURL(字符串:http://adall.ga/api/users/“+作者+”/image”)!
println(“请求:\(请求URL 2)”)
var request2=NSMutableURLRequest(URL:requestURL2)
request2.HTTPMethod=“GET”
request2.addValue(userToken!,用于HttpHeaderField:“tb token”)
让session2=NSURLSession.sharedSession()
让task2=session2.dataTaskWithRequest(request2){
数据、响应、错误
println(“响应=\(响应)”)
var dataString=NSString(数据:数据,编码:NSUTF8StringEncoding)
println(数据字符串)
self.imageUrls=(NSJSONSerialization.JSONObjectWithData(数据,选项:NSJSONReadingOptions.MutableContainers,错误:nil)为!NSDictionary)
//检查是否存在
让imageUrl=self.imageUrls[“url”]作为!字符串
让url=NSURL(字符串:“http://”+imageUrl)
self.urlsArray.append(url!)
println(self.urlsArray)
}
任务2.恢复()
}
}

您好,您可以使用它来加载图像,它将为您处理所有繁重的工作和缓存。以下是操作方法:

// Here we use the new provided sd_setImageWithURL: method to load the web image
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
                      placeholderImage:[UIImage imageNamed:@"placeholder.png"]
                             completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {... completion code here ...}];

这里有一个

添加了一个swift示例。我真的建议您使用这个库。您能给我举一个与我的代码相关的用法示例吗?在您可以看到的swift示例中,谢谢您。这正是您所需要的。您导入SDWebimagecache类别,然后将其与url和完成块一起使用。这确实很简单。在您的单元格中,用于XPath act在UIImageView上输入,并让他们在此类帮助下处理加载。如果此答案有助于您,请标记为正确并向上投票。谢谢。当然。只有一个问题:如何知道urlArray是否已满,以及如何重新加载表中的数据?谢谢