我正在练习一个有一个社交页面的示例应用程序。我试着用相应的媒体显示每条推文。我能得到文本和媒体,但不是一条推特,我能得到的进一步是显示媒体链接。如果有任何关于如何通过媒体发布推文的帮助,我们将不胜感激。为了使其更清晰,用户应该能够查看应用程序中的文本和任何图片/视频,而无需打开任何链接。
import UIKit
class ViewController: UIViewController,
UITableViewDelegate,UITableViewDataSource {
//importing objects
@IBOutlet weak var mytextfield: UITextField!
@IBOutlet weak var myLabel: UILabel!
@IBOutlet weak var myimageView: UIImageView!
@IBOutlet weak var myTableview: UITableView!
@IBOutlet weak var myScroll: UIScrollView!
var tweets:[String] = []
//Activity Indicator
var activityInd = UIActivityIndicatorView()
func startA()
{
UIApplication.shared.beginIgnoringInteractionEvents()
activityInd.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
activityInd.center = view.center
activityInd.startAnimating()
view.addSubview(activityInd)
}
//setting table view
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tweets.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
cell.mytextview.text = tweets[indexPath.row]
return cell
}
@IBAction func mysearchbutton(_ sender: UIButton) {
if mytextfield.text != ""
{
startA()
let user = mytextfield.text?.replacingOccurrences(of: " ", with: "")
getStuff(user: user!)
}
}
//Create a function that gets all the stuff
func getStuff(user:String)
{
let url = URL(string: "https://twitter.com/" + user)
let task = URLSession.shared.dataTask(with: url!) { (data,response, error) in
if error != nil
{
DispatchQueue.main.async
{
if let errorMessage = error?.localizedDescription
{
self.myLabel.text = errorMessage
}else{
self.myLabel.text = "There has been an error try again"
}
}
}else{
let webContent:String = String(data: data!,encoding: String.Encoding.utf8)!
if webContent.contains("<title>") && webContent.contains("data-resolved-url-large=\"")
{
//get user name
var array:[String] = webContent.components(separatedBy: "<title>")
array = array[1].components(separatedBy: " |")
let name = array[0]
array.removeAll()
//getprofile pic
array = webContent.components(separatedBy: "data-resolved-url-large=\"")
array = array[1].components(separatedBy: "\"")
let profilePic = array[0]
print(profilePic)
//get tweets
array = webContent.components(separatedBy: "data-aria-label-part=\"0\">")
//get tweets media
// array = webContent.components(separatedBy: "data-pre-embedded=\"true\" dir=\"ltr\" >")
array.remove(at: 0)
for i in 0...array.count-1
{
let newTweet = array[i].components(separatedBy: "<")
array[i] = newTweet[0]
}
self.tweets = array
DispatchQueue.main.async {
self.myLabel.text = name
self.updateImage(url: profilePic)
self.myTableview.reloadData()
self.activityInd.stopAnimating()
UIApplication.shared.endIgnoringInteractionEvents()
}
}else{
DispatchQueue.main.async {
self.myLabel.text = "User not found"
self.activityInd.stopAnimating()
UIApplication.shared.endIgnoringInteractionEvents()
}
}
}
}
task.resume()
}
//Function that gets profile pic data
func updateImage(url:String)
{
let url = URL(string: url)
let task = URLSession.shared.dataTask(with: url!){ (data, response, error) in
DispatchQueue.main.async
{
self.myimageView.image = UIImage(data: data!)
}
}
task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
myScroll.contentSize.height = 1000
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
最佳答案
@SYou可以在iOS中为你的应用程序使用TwitterKit SDK。Twitter SDK完全能够满足您的需求。无论你想要什么样的feed功能,你只需要在twitter工具包中配置它。
在显示Tweets时,可以为提要实现以下功能:
款式(深色或浅色)
颜色(文本、链接、背景)
动作按钮
要通知用户与Tweet交互的代理(TWTRTweetViewDelegate)
要显示tweets,可以执行以下操作:
显示tweets有两个选项:
您可以加载任何公共tweets(注意:要显示公共tweets,您需要公共Tweet id)
斯威夫特4
例如
//
// PublicTweets.swift
// TwitterFeedDemo
//
// Created by User on 21/12/17.
// Copyright © 2017 Test Pvt. Ltd. All rights reserved.
//
import UIKit
import TwitterKit
class PublicTweets : UITableViewController {
// setup a 'container' for Tweets
var tweets: [TWTRTweet] = [] {
didSet {
tableView.reloadData()
}
}
var prototypeCell: TWTRTweetTableViewCell?
let tweetTableCellReuseIdentifier = "TweetCell"
var isLoadingTweets = false
override func viewDidLoad() {
super.viewDidLoad()
if let user = Twitter.sharedInstance().sessionStore.session()?.userID {
Twitter.sharedInstance().sessionStore.logOutUserID(user)
}
self.tableView.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 0, right: 0)
// Create a single prototype cell for height calculations.
self.prototypeCell = TWTRTweetTableViewCell(style: .default, reuseIdentifier: tweetTableCellReuseIdentifier)
// Register the identifier for TWTRTweetTableViewCell.
self.tableView.register(TWTRTweetTableViewCell.self, forCellReuseIdentifier: tweetTableCellReuseIdentifier)
// Setup table data
loadTweets()
}
func loadTweets() {
// Do not trigger another request if one is already in progress.
if self.isLoadingTweets {
return
}
self.isLoadingTweets = true
// set tweetIds to find
let tweetIDs = ["944116014828138496","943585637881352192","943840936135741440"];
// Find the tweets with the tweetIDs
let client = TWTRAPIClient()
client.loadTweets(withIDs: tweetIDs) { (twttrs, error) -> Void in
// If there are tweets do something magical
if ((twttrs) != nil) {
// Loop through tweets and do something
for i in twttrs! {
// Append the Tweet to the Tweets to display in the table view.
self.tweets.append(i as TWTRTweet)
}
} else {
print(error as Any)
}
}
}
}
// MARK
// MARK: UITableViewDataSource UITableViewDelegate
extension PublicTweets {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// Return the number of Tweets.
return tweets.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Retrieve the Tweet cell.
let cell = tableView.dequeueReusableCell(withIdentifier: tweetTableCellReuseIdentifier, for: indexPath) as! TWTRTweetTableViewCell
// Assign the delegate to control events on Tweets.
cell.tweetView.delegate = self
cell.tweetView.showActionButtons = true
// Retrieve the Tweet model from loaded Tweets.
let tweet = tweets[indexPath.row]
// Configure the cell with the Tweet.
cell.configure(with: tweet)
// Return the Tweet cell.
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let tweet = self.tweets[indexPath.row]
self.prototypeCell?.configure(with: tweet)
return TWTRTweetTableViewCell.height(for: tweet, style: TWTRTweetViewStyle.compact, width: self.view.bounds.width , showingActions:true)
}
}
extension PublicTweets : TWTRTweetViewDelegate {
//Handle Following Events As Per Your Needs
func tweetView(_ tweetView: TWTRTweetView, didTap url: URL) {
}
func tweetView(_ tweetView: TWTRTweetView, didTapVideoWith videoURL: URL) {
}
func tweetView(_ tweetView: TWTRTweetView, didTap image: UIImage, with imageURL: URL) {
}
func tweetView(_ tweetView: TWTRTweetView, didTap tweet: TWTRTweet) {
}
func tweetView(_ tweetView: TWTRTweetView, didTapProfileImageFor user: TWTRUser) {
}
func tweetView(_ tweetView: TWTRTweetView, didChange newState: TWTRVideoPlaybackState) {
}
}
你也可以显示其他用户的tweets,只要有他们的屏幕名或Twitter用户id
例如。
//
// SelfTweets.swift
// TwitterFeedDemo
//
// Created by User on 21/12/17.
// Copyright © 2017 Test Pvt. Ltd. All rights reserved.
//
import Foundation
import UIKit
import TwitterKit
class SelfTweets: TWTRTimelineViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
if let user = Twitter.sharedInstance().sessionStore.session()?.userID {
let client = TWTRAPIClient()
self.dataSource = TWTRUserTimelineDataSource.init(screenName:"li_ios", userID: user, apiClient: client, maxTweetsPerRequest: 10, includeReplies: true, includeRetweets: false)
}
}
}
关于ios - 使用Swift IOS获取推文,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47921802/