我在社交媒体上练习很快,我正在学习如何将Twitter时间线添加到App App的教程。一切似乎都没问题,但唯一的问题是显示推文的表格是完全空的。代码如下......
import UIKit
import Social
import Accounts
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tweetTableView: UITableView!
var dataSource = [AnyObject]()
func getTimeLine() {
let account = ACAccountStore()
let accountType = account.accountType(
withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter)
account.requestAccessToAccounts(with: accountType, options: nil, completion: {(success, error) in
if success {
let arrayOfAccounts =
account.accounts(with: accountType)
if (arrayOfAccounts?.count)! > 0 {
let twitterAccount = arrayOfAccounts?.last as! ACAccount
let requestURL = URL(string:
"https://api.twitter.com/1.1/statuses/user_timeline.json")
let parameters = ["screen_name" : "@techotopia",
"include_rts" : "0",
"trim_user" : "1",
"count" : "20"]
let postRequest = SLRequest(forServiceType:
SLServiceTypeTwitter,
requestMethod: SLRequestMethod.GET,
url: requestURL,
parameters: parameters)
postRequest?.account = twitterAccount
postRequest?.perform(handler: {(responseData, urlResponse, error) in
do {
try self.dataSource = JSONSerialization.jsonObject(with: responseData!, options: JSONSerialization.ReadingOptions.mutableLeaves) as! [AnyObject]
if self.dataSource.count != 0 {
DispatchQueue.main.async() {
self.tweetTableView.reloadData()
}
}
} catch let error as NSError {
print("Data serialization error: \(error.localizedDescription)")
}
})
}
} else {
print("Failed to access account")
}
})
}
override func viewDidLoad() {
super.viewDidLoad()
tweetTableView.register(UITableViewCell.self,
forCellReuseIdentifier: "Cell")
getTimeLine()
tweetTableView.estimatedRowHeight = 50
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell =
tableView.dequeueReusableCell(withIdentifier: "Cell")
let row = indexPath.row
let tweet = self.dataSource[row]
cell!.textLabel!.text = tweet.object(forKey: "text") as? String
cell!.textLabel!.numberOfLines = 0
return cell!
}
}
感谢您的回答!谢谢!