关于iOS:如何将令牌和令牌密钥传递给OAuth Swift

how to pass token and token seceret to oauth swift

如何在OAuth Swift lib上传递令牌和令牌密钥

我在lib的git文档上找到了以下代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// create an instance and retain it
let oauthswift = OAuth1Swift(
    consumerKey:   "********",
    consumerSecret:"********"
)
// do your HTTP request without authorize
oauthswift.client.get("https://api.example.com/foo/bar",
    success: { response in
        //....
    },
    failure: { error in
        //...
    }
)

但是,除了consumerKey和consumerSecret外,我也有令牌和TokenSecret。 所以我可以在oAuthSwift lib中传递它。

我尝试了以下代码

1
2
3
4
5
6
let  oauthswift = OAuth1Swift(
            consumerKey:"102xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
            consumerSecret:"5xxxxxxxxxxxxxxxxxxxxxxxxxxx",
            token:"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
            tokenSeceret:"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
        )

但是它给出了错误"无法使用参数列表调用类型为'OAuth1Swift'的初始化程序"
这个库中有另一个初始化器,如下所示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// create an instance and retain it
oauthswift = OAuth1Swift(
    consumerKey:   "********",
    consumerSecret:"********",
    requestTokenUrl:"https://api.twitter.com/oauth/request_token",
    authorizeUrl:   "https://api.twitter.com/oauth/authorize",
    accessTokenUrl: "https://api.twitter.com/oauth/access_token"
)
// authorize
let handle = oauthswift.authorize(
    withCallbackURL: URL(string:"oauth-swift://oauth-callback/twitter")!,
    success: { credential, response, parameters in
      print(credential.oauthToken)
      print(credential.oauthTokenSecret)
      print(parameters["user_id"])
      // Do your request
    },
    failure: { error in
      print(error.localizedDescription)
    }            
)

但是我们没有这样的链接来获取令牌,而是使用了已经创建的令牌并进行加密


在呼叫请求之前使用以下两行

1
2
oauthswift.client.credential.oauth_token = {your stored token}
oauthswift.client.credential.oauth_token_secret = {your stored secret token}

即您的代码成为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// create an instance and retain it
let oauthswift = OAuth1Swift(
    consumerKey:   "********",
    consumerSecret:"********"
)

//Set Token and TokenSecret
    oauthswift.client.credential.oauth_token ="asxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
    oauthswift.client.credential.oauth_token_secret ="1cxxxxxxxxxxxxxxxxxxxxxxx"


// do your HTTP request
oauthswift.client.get("https://api.example.com/foo/bar",
    success: { response in
        //....
    },
    failure: { error in
        //...
    }
)