PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 15, 2022

[FIXED] How to receive an output for a method from a closure in Swift?

 August 15, 2022     closures, function, ios, output, swift     No comments   

Issue

How to receive an output of an array of [TweetSentimentClassifierInput] objects to send it further to my prediction model?

I have the array but inside a closure which turns it unavailable to return as a method output. If I initialize an empty array outside the closure then the output is always an empty array since fetch closure takes time to be completed.

Code

struct TweetFetcher {

   let tweetCount = 100
   let swifter = Swifter(consumerKey: key, consumerSecret: secret)

func fetchTweets(with searchText: String) -> [TweetSentimentClassifierInput] {
    
    swifter.searchTweet(using: searchText, lang: "en", count: tweetCount, tweetMode: .extended) {(results, searchMetadata) in
        var tweets = [TweetSentimentClassifierInput]()
        let data = results.description.data(using: .utf8)

        do {
            let decodedData = try JSONDecoder().decode([TweetData].self, from: data!)
        } catch {
            print("Error with decoding, \(error)")
        }

        for tweet in decodedData {
            let tweetForClassification = TweetSentimentClassifierInput(text: tweet.full_text)
            tweets.append(tweetForClassification)
        }
    } failure: { (error) in
        print("Error with the Twitter API request, \(error)")
    }
}
}

How can I return a non-empty array from a closure as a method output?


Solution

You should use a completionHandler concept to achieve async operations like this:

struct TweetFetcher {
    let tweetCount = 100
    let swifter = Swifter(consumerKey: key, consumerSecret: secret)
    
    func fetchTweets(with searchText: String, completion: @escaping ([TweetSentimentClassifierInput]?, Error?) -> Void) {
        
        swifter.searchTweet(using: searchText, lang: "en", count: tweetCount, tweetMode: .extended) {(results, searchMetadata) in
            var tweets = [TweetSentimentClassifierInput]()
            let data = results.description.data(using: .utf8)
            
            do {
                let decodedData = try JSONDecoder().decode([TweetData].self, from: data!)
            } catch {
                print("Error with decoding, \(error)")
                completion(nil, error)
            }
            
            for tweet in decodedData {
                let tweetForClassification = TweetSentimentClassifierInput(text: tweet.full_text)
                tweets.append(tweetForClassification)
            }
            completion(tweets, nil)
        } failure: { (error) in
            print("Error with the Twitter API request, \(error)")
            completion(nil, error)
        }
    }
}

Usage

let fetcher = TweetFetcher()
fetcher.fetchTweets(with: "Keyword...") { tweets, error in
    if let error = error {
        print(error.localizedDescription)
    } else {
        // Use tweets array content here ...
    }
}


Answered By - rami
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing