ios - 如何从 Swift 中的闭包返回值?

标签 ios swift twitter closures twitter-fabric

所以我正在使用 fabric 插件/Twitter-kit 在我的应用程序中使用 twitter api。我想获取名人个人资料图片的图片网址。下面是我的代码。

func getImageURL(celebrity :String) -> String{

    var imageURL = ""
    let client = TWTRAPIClient()
    let statusesShowEndpoint = userSearch
    let params = ["q": celebrity,
                  "page" : "1",
                  "count" : "1"
                  ]
    var clientError : NSError?

    let request = client.URLRequestWithMethod("GET", URL: statusesShowEndpoint, parameters: params, error: &clientError)

     client.sendTwitterRequest(request) { (response, data, connectionError) -> Void in
        if connectionError != nil {
            print("Error: \(connectionError)")
        }

        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data!, options: [])
            print("json: \(json)")

            let profileImageURL: String? = json[0].valueForKey("profile_image_url_https") as? String

            imageURL =  self.cropTheUrlOfImage(profileImageURL!)
            print(imageURL)

            //how do i return the value back. confused ?????
            return imageURL

        } catch let jsonError as NSError {
            print("json error: \(jsonError.localizedDescription)")
        }
    }

    return imageURL

}

我不知道如何返回值,因为该方法在闭包完全执行之前完成。我是 swift 的新手,感谢任何帮助。

我想在 tableview 的 cellForRowIndexPath 中使用这个方法从 imageURl 下载图像。

最佳答案

您需要从@escaping 闭包中返回。 改变功能

func getImageURL(celebrity: String) -> String {

}

func getImageURL(celebrity: String, completion: @escaping(String)->()) {

      // your code
      completion(imgURL)
}

你可以按照下面的方式使用它

getImageURL(celebrity: String) { (imgURL) in

      self.imgURL = imgURL // Using self as the closure is running in background
}

这是一个例子,我如何编写多个带有闭包的方法来完成。

class ServiceManager: NSObject {

//  Static Instance variable for Singleton
static var sharedSessionManager = ServiceManager()

//  Function to execute GET request and pass data from escaping closure
func executeGetRequest(with urlString: String, completion: @escaping (Data?) -> ()) {

    let url = URL.init(string: urlString)
    let urlRequest = URLRequest(url: url!)

    URLSession.shared.dataTask(with: urlRequest) { (data, response, error) in
        //  Log errors (if any)
        if error != nil {
            print(error.debugDescription)
        } else {
            //  Passing the data from closure to the calling method
            completion(data)
        }
    }.resume()  // Starting the dataTask
}

//  Function to perform a task - Calls executeGetRequest(with urlString:) and receives data from the closure.
func downloadMovies(from urlString: String, completion: @escaping ([Movie]) -> ()) {
    //  Calling executeGetRequest(with:)
    executeGetRequest(with: urlString) { (data) in  // Data received from closure
        do {
            //  JSON parsing
            let responseDict = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any]
            if let results = responseDict!["results"] as? [[String:Any]] {
                var movies = [Movie]()
                for obj in results {
                    let movie = Movie(movieDict: obj)
                    movies.append(movie)
                }
                //  Passing parsed JSON data from closure to the calling method.
                completion(movies)
            }
        } catch {
            print("ERROR: could not retrieve response")
        }
    }
  }
}

下面是我如何使用它传递值的示例。

ServiceManager.sharedSessionManager.downloadMovies(from: urlBase) { (movies : [Movie]) in   // Object received from closure
      self.movies = movies
      DispatchQueue.main.async {
            //  Updating UI on main queue
            self.movieCollectionView.reloadData()
      }
}

我希望这可以帮助任何寻找相同解决方案的人。

关于ios - 如何从 Swift 中的闭包返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38296910/

相关文章:

swift - NSKeyValueObservation observe() 闭包中是否需要弱 self ?

xcode - 我无法捕获此功能的错误

Swift 4. 使用 PAT。允许相互引用的协议(protocol)吗?我收到一个我不明白的错误

android - 如何退出推特

android - Facebook Messenger API - 永久菜单不适用于移动设备

ios - SLComposeViewController 共享文本出现空白的问题 ios9

ios - 如何以编程方式向 Eureka 中的表单添加顶部导航?

ios - 当应用程序处于终止模式时如何从推送通知重定向到特定的 View Controller

Twitter 用户代理分享

c++ - 如何开始使用 twitCurl?