我创建了名为importStories()
的方法,该方法使用第三方库Swifter调用getStatusesUserTimelineWithUserID
方法从Twitter导入时间轴数据。问题是该方法在任何值设置为twitterData之前返回。任何建议表示赞赏。
func importStories() -> [String] {
let twitterAccount = Swifter(REDACTED)
var twitterData = [String]()
twitterAccount.getStatusesUserTimelineWithUserID("REDACTED", count: 0, sinceID: nil, maxID: nil, trimUser: true, contributorDetails: false, includeEntities: true, success: { (statuses) -> Void in
if statuses != nil {
for var i=0; i<statuses!.count; i++ {
twitterData.append(statuses![i]["text"].string!)
}
}
}) { (error) -> Void in
}
return twitterData
}
public func getStatusesUserTimelineWithUserID(userID: String, count: Int?, sinceID: Int?, maxID: Int?, trimUser: Bool?, contributorDetails: Bool?, includeEntities: Bool?, success: ((statuses: [JSONValue]?) -> Void)?, failure: FailureHandler?) {
var parameters: Dictionary<String, AnyObject> = ["user_id": userID]
self.getTimelineAtPath("statuses/user_timeline.json", parameters: [:], count: count, sinceID: sinceID, maxID: maxID, trimUser: trimUser, contributorDetails: contributorDetails, includeEntities: includeEntities, success: success, failure: failure)
}
答案 0 :(得分:0)
这是我经常使用的模式。它可以通过一些类型的比例看起来更好看,但我没有使用任何代码。
这里的关键是通过调用由调用代码提供的块来返回结果。
func importStoriesWithSuccess(success:(result: [String]) -> Void, failure: (error: NSError) -> Void) {
let twitterAccount = Swifter(REDACTED)
var twitterData = [String]()
twitterAccount.getStatusesUserTimelineWithUserID("REDACTED", count: 0, sinceID: nil, maxID: nil, trimUser: true, contributorDetails: false, includeEntities: true, success: { (statuses) -> Void in
if statuses != nil {
for var i=0; i<statuses!.count; i++ {
twitterData.append(statuses![i]["text"].string!)
}
success(result: twitterData)
}
}) { (error) -> Void in
failure(error: error)
}
}
正如cjcoax已经提到的,在你的代码中,在twitterAccount执行你提供给它的块之前返回了twitterData。这就是你的twitterData为空的原因。