2016-04-23 4 views
0

同じクラス(学校)にある私のParseデータベースからユーザーのtableViewを作成しようとしています。すべてのユーザーはユーザー名を持っている必要がありますが、すべてのユーザーにそのフルネームを与えたり、プロフィール画像を設定したりするわけではありません。私はこのコードを使用しています:特定のテーブルにアイテムを追加する利用可能であれば行を表示する

let studentsQuery = PFQuery(className:"_User") 
studentsQuery.whereKey("objectId", containedIn: studentsArray! as! [AnyObject]) 

let query2 = PFQuery.orQueryWithSubqueries([studentsQuery]) 

query2.findObjectsInBackgroundWithBlock { 
    (results: [PFObject]?, error: NSError?) -> Void in 

    if error != nil { 

     // Display error in tableview 

    } else if results! == [] { 

     spinningActivity.hideAnimated(true) 

     print("error") 

    } else if results! != [] { 

     if let objects = results { 

      for object in objects { 

       if object.objectForKey("full_name") != nil { 

        let studentName = object.objectForKey("full_name")! as! String 

        self.studentNameResults.append(studentName) 


       } 

       if object.objectForKey("username") != nil { 

        let studentUsername = object.objectForKey("username")! as! String 

        self.studentUsernameResults.append(studentUsername) 

       } 

       if object.objectForKey("profile_picture") != nil { 

        let studentProfilePictureFile = object.objectForKey("profile_picture") as! PFFile 

        studentProfilePictureFile.getDataInBackgroundWithBlock({ (image: NSData?, error: NSError?) in 

         if error == nil { 

          let studentProfilePicture : UIImage = UIImage(data: image!)! 
          self.studentProfilePictureResults.append(studentProfilePicture) 

         } else { 

          print("Can't get profile picture") 

          // Can't get profile picture 

         } 

         self.studentsTableView.reloadData() 

        }) 

        spinningActivity.hideAnimated(true) 

       } else { 

        // no image 

       } 

      } 
     } 
} else { 

    spinningActivity.hideAnimated(true) 

    print("error") 

} 
} 

このコードは、すべてのユーザーがusername、full_name、およびprofile_pictureを持っていれば正常に動作します。しかし、ユーザーのユーザー名のtableViewを取得し、ユーザーの名前または画像をユーザーの対応するtableViewCellに追加する方法を把握することはできません。パースから引き出さユーザーの画像の配列、ユーザ名、および名前の結果から来

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

     return studentUsernameResults.count 

} 


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

     let cell = tableView.dequeueReusableCellWithIdentifier("studentsCell", forIndexPath: indexPath) as! StudentsInClassInformationTableViewCell 

     cell.studentProfilePictureImageView.layer.cornerRadius = cell.studentProfilePictureImageView.frame.size.width/2 
     cell.studentProfilePictureImageView.clipsToBounds = true 

     cell.studentProfilePictureImageView.image = studentProfilePictureResults[indexPath.row] 

     cell.studentUsernameLabel.text = studentUsernameResults[indexPath.row] 

     cell.studentNameLabel.text = studentNameResults[indexPath.row] 


     return cell 

} 

studentProfilePictureResultsstudentUsernameResults、およびstudentNameResults:ここに私のtableViewが設定されている方法です。ユーザーがプロフィール写真を持っていない場合は、エラーIndex is out of rangeが表示されます。明らかに、これは、3つの名前、3つのユーザー名、2つのピクチャしか存在せず、Xcodeはセルの構成方法を知らないことを意味します。私の質問:テーブルビューを設定してユーザーのユーザー名を設定し、名前とプロフィールの画像を同じセルに配置するにはどうすればよいですか?

+0

別々のアレイを保管しないでください。 PFObjectsの1つの配列を格納すると、写真の[username(string):UIImage]辞書を使用することをお勧めします – Paulw11

+0

@ Paulw11ユーザーのユーザー名、名前、画像を照会すると、一度、あなたが話しているように(結果を1つの配列に格納する)。ユーザー名、名前、画像を一緒に保存するにはどうすればいいですか?私は辞書ではあまりプレイしていないが、2つの結果しか保存できないと思った。どのようにして3つすべてを保存できますか? –

答えて

1

異なるアトリビュートを異なる配列に格納しようとすると問題が発生します。これは、特定のユーザにアトリビュートがない場合に問題が発生するためです。あなたはオプション配列を使うことができるので、不在属性にはnilを格納できますが、PFObject自体を1つの配列に格納し、属性を分割するのではなくcellForRowAtIndexPathの属性にアクセスする方がはるかに簡単です。

写真を取得するには別々の非同期操作が必要なため、別々に保存することができます。配列を使用して検索した写真を格納するのではなく、同じ順序の問題がある場合は、ユーザーIDで索引付けされた辞書を使用できます。多数の学生にとってはcellForRowAtIndexPathのように写真をダウンロードするのにSDWebImageのようなものを使う方が効率的でしょう。

// these are instance properties defined at the top of your class 
var students: [PFObject]? 
var studentPhotos=[String:UIImage]() 

// This is in your fetch function 
let studentsQuery = PFUser.Query() 
    studentsQuery.whereKey("objectId", containedIn: studentsArray! as! [AnyObject]) 

let query2 = PFQuery.orQueryWithSubqueries([studentsQuery]) 

query2.findObjectsInBackgroundWithBlock { 
    (results: [PFObject]?, error: NSError?) -> Void in 
    guard (error == nil) else { 
     print(error) 
     spinningActivity.hideAnimated(true) 
     return 
    } 

    if let results = results { 
     self.students = results 
      for object in results { 
       if let studentProfilePictureFile = object.objectForKey("profile_picture") as? PFFile { 
        studentProfilePictureFile.getDataInBackgroundWithBlock({ (image: NSData?, error: NSError?) in 
        guard (error != nil) else { 
         print("Can't get profile picture: \(error)") 
         return 
        } 

       if let studentProfilePicture = UIImage(data: image!) { 
        self.studentPhotos[object["username"]!]=studentProfilePicture 
       } 
      } 
    } 
    spinningActivity.hideAnimated(true) 
    self.tableview.reloadData() 
} 

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
    if self.students != nil { 
     return self.students!.count 
    } 
    return 0 
} 

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

    let cell = tableView.dequeueReusableCellWithIdentifier("studentsCell", forIndexPath: indexPath) as! StudentsInClassInformationTableViewCell 

    cell.studentProfilePictureImageView.layer.cornerRadius = cell.studentProfilePictureImageView.frame.size.width/2 
    cell.studentProfilePictureImageView.clipsToBounds = true 

    let student = self.students[indexPath.row] 

    if let studentPhoto = self.studentPhotos[student["username"]!] { 
     cell.studentProfilePictureImageView.image = studentProfilePictureResults[indexPath.row] 
    } else { 
     cell.studentProfilePictureImageView.image = nil 
    } 

    cell.studentUsernameLabel.text = student["username"]! 

    if let fullName = student["full_name"] { 
     cell.studentNameLabel.text = fullName 
    } else { 
     cell.studentNameLabel.text = "" 
    return cell 
} 

その他のいくつかのポインタ。

  • フィールド名の単語を区切るために_を使用すると、実際にはiOSの世界では使用されません。他のクラスメンバーの配列を指定する必要がないように、フィールドまたは参照オブジェクトがclassの場合、Parseクエリがより効率的になるようです。
+0

あなたは命を救う人、ポール!私はちょっとしたデバッグをしなければなりませんでしたが、私が持っていたいくつかの問題に基づいて数日で答えを編集しますが、全体的にクリーンで簡単な方法でした!再度、感謝します! –

関連する問題