Ios 从联机数据库填充UICollectionView

Ios 从联机数据库填充UICollectionView,ios,swift,uicollectionview,ios-lifecycle,Ios,Swift,Uicollectionview,Ios Lifecycle,我正在创建一个简单的聊天应用程序,它有一个加载屏幕,如果用户未登录,则可以切换到登录屏幕,如果用户已登录,则可以直接切换到聊天。聊天记录显示在UICollectionView中。当我第一次进行测试时,我用我在类本身中声明的虚拟数据填充它,并且一切正常。现在,我从加载屏幕中的在线数据库中获取用户的聊天记录,并将其存储在一个名为user\u chats的数组中,该数组是全局声明的 我使用以下代码填充UICollectionView: func collectionView(collectionVi

我正在创建一个简单的聊天应用程序,它有一个加载屏幕,如果用户未登录,则可以切换到登录屏幕,如果用户已登录,则可以直接切换到聊天。聊天记录显示在
UICollectionView
中。当我第一次进行测试时,我用我在类本身中声明的虚拟数据填充它,并且一切正常。现在,我从加载屏幕中的在线数据库中获取用户的聊天记录,并将其存储在一个名为
user\u chats
的数组中,该数组是全局声明的

我使用以下代码填充
UICollectionView

func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
   // getUserChats()
    return user_chats.count

}

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

let cell = collectionView.dequeueReusableCellWithReuseIdentifier("chat_cell" , forIndexPath: indexPath) as! SingleChat

cell.chatName?.text = user_chats[indexPath.row].chat_partner!.name
cell.chatTextPreview?.text = user_chats[indexPath.row].chat_messages!.last!.text
let profile_pic_URL = NSURL(string : user_chats[indexPath.row].chat_partner!.profile_pic!)
downloadImage(profile_pic_URL!, imageView: cell.chatProfilePic)
cell.chatProfilePic.layer.cornerRadius = 26.5
cell.chatProfilePic.layer.masksToBounds = true

    let dividerLineView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
        return view
    }()
    dividerLineView.translatesAutoresizingMaskIntoConstraints = false

    cell.addSubview(dividerLineView)
    cell.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-1-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": dividerLineView]))
    cell.addSubview(dividerLineView)
    cell.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[v0(1)]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": dividerLineView]))
    return cell

}

func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {

    self.performSegueWithIdentifier("showChat", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

    if (segue.identifier == "showChat") {

        let IndexPaths = self.collectionView!.indexPathsForSelectedItems()!
        let IndexPath = IndexPaths[0] as NSIndexPath
        let vc = segue.destinationViewController as! SingleChatFull

        vc.title = user_chats[IndexPath.row].chat_partner!.name
    }

}
数据提取:

func getUserChats() {
    let scriptUrl = "*****"
    let userID = self.defaults.stringForKey("userId")
    let params = "user_id=" + userID!
    let myUrl = NSURL(string: scriptUrl);
    let request: NSMutableURLRequest = NSMutableURLRequest(URL: myUrl!)
    request.HTTPMethod = "POST"
    let data = params.dataUsingEncoding(NSUTF8StringEncoding)
    request.timeoutInterval = 10
    request.HTTPBody=data
    request.HTTPShouldHandleCookies=false
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    let queue:NSOperationQueue = NSOperationQueue()
    NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
        do {
            if (data != nil) {
                do {
                    var dataString = String(data: data!, encoding: NSUTF8StringEncoding)
                    var delimiter = "]"
                    var token = dataString!.componentsSeparatedByString(delimiter)
                    dataString = token[0] + "]"
                    print(dataString)
                    let data_fixed = dataString!.dataUsingEncoding(NSUTF8StringEncoding)
                    do {
                        let jsonArray = try NSJSONSerialization.JSONObjectWithData(data_fixed!, options:[])


                        // LOOP THROUGH JSON ARRAY AND FETCH VALUES
                        for anItem in jsonArray as! [Dictionary<String, AnyObject>] {
                            let curr_chat = Chat()
                            if let chatId = anItem["chatId"] as? String {
                                curr_chat.id = chatId
                            }
                            let friend = Friend()
                            let user1id = anItem["user1_id"] as! String
                            let user2id = anItem["user2_id"] as! String
                            if (user1id == userID) {
                                if let user2id = anItem["user2_id"] as? String {
                                    friend.id = user2id
                                }
                                if let user2name = anItem["user2_name"] as? String {
                                    friend.name = user2name
                                }
                                if let user2profilepic = anItem["user2_profile_pic"] as? String {
                                    friend.profile_pic = user2profilepic
                                }
                            }
                            else if (user2id == userID){
                                if let user1id = anItem["user1_id"] as? String {
                                    friend.id = user1id
                                }
                                if let user1name = anItem["user1_name"] as? String {
                                    friend.name = user1name
                                }
                                if let user1profilepic = anItem["user1_profile_pic"] as? String {
                                    friend.profile_pic = user1profilepic
                                }
                            }

                            curr_chat.chat_partner = friend

                            var chat_messages = [Message]()
                            if let dataArray = anItem["message"] as? [String : AnyObject] {
                                for (_, messageDictionary) in dataArray {
                                    if let onemessage = messageDictionary as? [String : AnyObject] {                                        let curr_message = Message()
                                        if let messageid = onemessage["message_id"] as? String {
                                            curr_message.id =  messageid
                                        }
                                        if let messagedate = onemessage["timestamp"] as? String {
                                            let dateFormatter = NSDateFormatter()
                                            dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
                                            let date = dateFormatter.dateFromString(messagedate)
                                            curr_message.date = date
                                        }
                                        if let messagesender = onemessage["sender"] as? String {

                                            curr_message.sender = messagesender
                                        }
                                        if let messagetext = onemessage["text"] as? String {
                                            curr_message.text = messagetext
                                        }
                                        chat_messages.append(curr_message)
                                    }}
                            }

                            curr_chat.chat_messages = chat_messages
                            user_chats.append(curr_chat)
                        }

                    }
                    catch {
                        print("Error: \(error)")
                    }
                }
//                       NSUserDefaults.standardUserDefaults().setObject(user_chats, forKey: "userChats")

            }
            else {
                dispatch_async(dispatch_get_main_queue(), {
                    let uiAlert = UIAlertController(title: "No Internet Connection", message: "Please check your internet connection.", preferredStyle: UIAlertControllerStyle.Alert)

                    uiAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { action in
                        self.dismissViewControllerAnimated(true, completion:nil)
                    }))
                    self.presentViewController(uiAlert, animated: true, completion: nil)
                })
            }

        } catch _ {
            NSLog("error")
        }

    })
}
func getUserChats(){
让scriptUrl=“*******”
让userID=self.defaults.stringForKey(“userID”)
让params=“user_id=”+userID!
让myUrl=NSURL(字符串:scriptUrl);
let请求:NSMutableURLRequest=NSMutableURLRequest(URL:myUrl!)
request.HTTPMethod=“POST”
let data=params.dataUsingEncoding(NSUTF8StringEncoding)
request.timeoutInterval=10
request.HTTPBody=data
request.HTTPShouldHandleCookies=false
UIApplication.sharedApplication().networkActivityIndicatorVisible=true
let队列:NSOperationQueue=NSOperationQueue()
NSURLConnection.sendAsynchronousRequest(请求,队列:队列,completionHandler:{(响应:NSURLResponse?,数据:NSData?,错误:NSError?)->Void in
做{
如果(数据!=nil){
做{
var dataString=String(数据:data!,编码:NSUTF8StringEncoding)
var delimiter=“]”
var token=dataString!。componentsSeparatedByString(分隔符)
数据字符串=令牌[0]+“]”
打印(数据字符串)
let data\u fixed=dataString!.dataUsingEncoding(NSUTF8StringEncoding)
做{
让jsonArray=try NSJSONSerialization.JSONObjectWithData(数据已修复,选项:[])
//循环JSON数组并获取值
用于jsonArray中的anItem as![词典]{
让curr_chat=chat()
如果让chatId=anItem[“chatId”]作为字符串{
curr\u chat.id=chatId
}
让朋友=朋友
让user1id=anItem[“user1\u id”]作为!字符串
让user2id=anItem[“user2_id”]作为!字符串
if(user1id==userID){
如果让user2id=anItem[“user2_id”]作为字符串{
friend.id=user2id
}
如果让user2name=anItem[“user2_name”]作为字符串{
friend.name=user2name
}
如果让user2profilepic=anItem[“user2\u profile\u pic”]作为?字符串{
friend.profile\u pic=user2profilepic
}
}
else if(user2id==userID){
如果让user1id=anItem[“user1\u id”]作为字符串{
friend.id=user1id
}
如果让user1name=anItem[“user1_name”]作为字符串{
friend.name=user1name
}
如果让user1profilepic=anItem[“user1\u profile\u pic”]作为字符串{
friend.profile\u pic=user1profilepic
}
}
curr\u chat.chat\u partner=朋友
var chat_messages=[Message]()
如果让dataArray=anItem[“message”]作为?[字符串:AnyObject]{
对于dataArray中的(_,messageDictionary){
如果让onemessage=messageDictionary作为?[String:AnyObject]{let curr\u message=message()
如果让messageid=onemessage[“message_id”]作为?字符串{
curr_message.id=messageid
}
如果让messagedate=onemessage[“timestamp”]作为字符串{
让dateFormatter=NSDateFormatter()
dateFormatter.dateFormat=“yyyy-MM-dd HH:MM:ss”
让date=dateFormatter.dateFromString(messagedate)
curr_message.date=日期
}
如果让messagesender=onemessage[“sender”]作为?字符串{
curr_message.sender=messagesender
}
如果让messagetext=onemessage[“text”]作为字符串{
curr_message.text=messagetext
}
聊天信息。附加(当前信息)
}}
}
curr\u chat.chat\u messages=聊天信息
用户\u chats.append(curr\u chat)
}
}
抓住{
打印(“错误:\(错误)”)
}
}
//NSUserDefaults.standardUserDefaults().setObject(用户聊天,forKey:“用户聊天”)
}
否则{
dispatc
dispatch_async(dispatch_get_main_queue()) {
        self.collectionView.reloadData()
}
protocol ChatsDelegate {
   func didUpdateChats(chatsArray: NSArray)
}
user_chats.append(cur_chat)
self.delegate.didUpdateChats(user_chats)
class viewController: ChatsDelegate, ... {
...
   func didUpdateChats(chatsArray: NSArray) {
      dispatch_async(dispatch_get_main_queue()) {
         self.collectionView.reloadData()
      }
   }
func getUserChats(completionHandler: (loaded: Bool, dataNil: Bool) -> ()) -> (){
        NSURLConnection.sendAsynchronousRequest(request, queue: queue, completionHandler:{ (response: NSURLResponse?, data: NSData?, error: NSError?) -> Void in
            do {
                if (data != nil) {
                    do {
                        var dataString = String(data: data!, encoding: NSUTF8StringEncoding)
                        var delimiter = "]"
                        var token = dataString!.componentsSeparatedByString(delimiter)
                        dataString = token[0] + "]"
                        print(dataString)
                        let data_fixed = dataString!.dataUsingEncoding(NSUTF8StringEncoding)
                        do {
                            let jsonArray = try NSJSONSerialization.JSONObjectWithData(data_fixed!, options:[])

                            // LOOP THROUGH JSON ARRAY AND FETCH VALUES
                            completionHandler(loaded: true, dataNil: false)
                        }
                        catch {
                            print("Error: \(error)")
                        }
                    }
                }
                else {
                    //Handle error or whatever you wish
                    completionHandler(loaded: true, dataNil: true)
                }

            } catch _ {
                NSLog("error")
            }
override func viewDidLoad() {
        getUserChats(){
            status in
            if status.loaded == true && status.dataNil == false{
                self.collectionView?.reloadData()
            }
        }
    }