使用Swift IOS获取推文

时间:2017-12-21 09:27:00

标签: ios arrays swift twitter

我在具有社交Feed页面的示例应用程序上练习。我试图用相应的媒体显示每条推文。我能够得到文本和媒体,但不是一条推文,我可以得到的更多是显示媒体链接。任何有关如何使用显示的媒体获得推文的帮助将不胜感激。为了更清楚,用户应该能够从应用程序中查看文本和任何图片/视频,而无需打开任何链接。

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


}

1 个答案:

答案 0 :(得分:1)

@S您可以在iOS中使用TwitterKit SDK作为您的应用。 Twitter SDK完全能够满足您的需求。无论您想要什么样的Feed功能,只需在twitter工具包中进行配置即可。

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

风格(黑暗或光明) 颜色(文字,链接,背景) 动作按钮 委托人(TWTRTweetViewDelegate)将收到用户与Tweet的交互通知

要显示推文,您可以这样做:

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

  • 您可以加载任何公开推文(注意:显示公开推文需要公开推文ID)

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

}