我正在编写我的第一个iOS应用程序。它包括通过OAuth2Client进行的API调用。
问题在于调用AdvAPI getUser函数。 GET请求是通过NXOAuth2Request进行的,它处理responseHandler中的响应数据,变量result被设置为NSDictionary。但是,在XOAuth2Request函数之外无法访问结果。如何获得结果并从getUser返回?
谢谢!
import Foundation
class AdvAPI {
var store : NXOAuth2AccountStore
var account : NXOAuth2Account?
init(){
self.store = NXOAuth2AccountStore.sharedStore() as NXOAuth2AccountStore
self.store.setClientID(
"test",
secret: "test",
authorizationURL: NSURL.URLWithString("http://localhost:3000/oauth/authorize"),
tokenURL: NSURL.URLWithString("http://localhost:3000/oauth/token"),
redirectURL: NSURL.URLWithString("http://localhost:3000/oauth/connect"),
forAccountType: "AdventureApp"
)
self.account = self.store.accountsWithAccountType("AdventureApp")[0]
}
func getUser(parameters : NSDictionary=[String: AnyObject]()) -> NSDictionary {
NXOAuth2Request.performMethod("GET",
onResource: NSURL.URLWithString("http://localhost:3000/api/v1/me"),
usingParameters: parameters,
withAccount: self.account,
sendProgressHandler: nil,
responseHandler: {(response: NSURLResponse?, responseData: NSData?, error: NSError?) in
var jsonError: NSError
var result = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
}
)
return result
}
}
答案 0 :(得分:1)
getUser函数在NXOAuth2Request完成之前返回,因此永远不会设置结果变量。
要解决此问题,唯一的选择似乎是在请求完成时从responseHandler中调用回调。
func getUser(parameters : NSDictionary=[String: AnyObject]()) {
NXOAuth2Request.performMethod("GET",
onResource: NSURL.URLWithString("http://localhost:3000/api/v1/me"),
usingParameters: parameters,
withAccount: self.account,
sendProgressHandler: nil,
responseHandler: {(response: NSURLResponse?, responseData: NSData?, error: NSError?) in
var jsonError: NSError
var result = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
self.delegate.didReceiveAPIResult(result)
}
)
}