繁体   English   中英

使用Swift IOS获取推文

[英]Fetching Tweets with Swift IOS

我正在使用具有社交订阅源页面的示例应用程序进行练习。 我正在尝试显示每个带有相应媒体的推文。 我能够获得文本和媒体,但无法获得一则鸣叫,而我能获得的进一步效果是显示媒体链接。 任何有关如何通过显示的媒体获取推文的帮助将不胜感激。 为了使其更清晰,用户应该能够从应用程序中查看文本和任何图片/视频,而无需打开任何链接。

 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.
}


}

@S您可以在iOS中为应用程序使用TwitterKit SDK。 Twitter SDK完全可以满足您的需求。 无论您想要什么提要功能,都只需要在twitter工具包中对其进行配置。

显示推文时,您可以为Feed实施以下功能:

样式(深色或浅色)颜色(文本,链接,背景)操作按钮通知用户与Tweet交互的委托(TWTRTweetViewDelegate)

要显示推文,您可以执行以下操作:

要显示推文,您有两种选择:

  • 您可以加载任何公共推文(注意:要显示公共推文,您需要公共推文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) {

    }

}
  • 您还可以通过仅具有其ScreenName或Twitter UserID来显示其他用户的推文

例如

//
//  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)
        }
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM