博客> 6.24 weibosdk登录和授权
6.24 weibosdk登录和授权
2019-11-14 14:38 评论:0 阅读:1111 qq139391025
ios swift weibosdk

说来weiboSDK也是奇怪,有个自带的登录,几行代码就能搞定。 在AppDelegate.swift文件中添加两行代码

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject:   AnyObject]?) -> Bool {
    WeiboSDK.enableDebugMode(true)
    WeiboSDK.registerApp(key)
    // Override point for customization after application launch.
    return true
}

其中appKey就是我们在微博开放平台注册获得的key 接着在我们想要的地方添加

@IBAction func onLoginBtn(sender: AnyObject) {
    let request = WBAuthorizeRequest.request() as? WBAuthorizeRequest
    request?.redirectURI = redirectURI
    request?.scope = "all"
    WeiboSDK.sendRequest(request) 
}

但这还是需要响应一下单击事件,并不能直接弹出来。。。找了几个方法还是不知道怎么解决。。。 再来就是授权登录了。这个就拼接拼接url 贴到自己的webview上就行,回调之后再请求第二部获得token

 var web = UIWebView()
func loadAuthor()  {
    let appKey = "3003035783"
    let redirect_uri = "https://api.weibo.com/oauth2/default.html"
    let url = NSURL.init(string: "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirect_uri)&response_type=code")
    let request = NSURLRequest.init(URL: url!)
    web.loadRequest(request)
    web.delegate = self
    self.view.addSubview(web)
    web.snp_makeConstraints(closure: { (make) in
        make.top.equalTo(self.view).offset(80)
        make.bottom.equalTo(self.view).offset(-40)
        make.left.right.equalTo(self.view).offset(0)
    })
}

然后我们到web view的代理里面获取

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
        let urlString = request.URL?.absoluteString
        //是否包含回调地址
        if urlString!.hasPrefix(redirectURI) {
            let query = request.URL?.query
            //截取字符串code=后面的值
            let code = query?.substringFromIndex("code=".endIndex)
            getToken(code!)
            dismissWeb()
            return false
        }
        return true
    }

获得code我们就可以请求token了

func getToken(code:String){
    //设置参数
    let urlStr = "https://api.weibo.com/oauth2/access_token"
    let appkey = "3003035783"
    let secret = "65a3834c227fd013384defd198f693f2"
    let grant_type = "authorization_code"
    let code = code
    let redirect_uri = redirectURI
    let param = ["client_id":appkey,
                 "client_secret":secret,
                 "grant_type":grant_type,
                 "code":code,
                 "redirect_uri":redirect_uri
                ]
    Alamofire.request(.POST, urlStr, parameters: param, encoding:.URL, headers: nil).responseJSON {
        response in
        print(response.result.value)
        let JSON = response.result.value
        let token = JSON?.objectForKey("access_token")
        let uid = JSON?.objectForKey("uid")
        NSUserDefaults.standardUserDefaults().setObject(token, forKey: "accessToken")
        NSUserDefaults.standardUserDefaults().setObject(uid, forKey: "userId")
    }
    let token2 = NSUserDefaults.standardUserDefaults().objectForKey("accessToken") as! String
    let userId2 = NSUserDefaults.standardUserDefaults().objectForKey("userId") as! String
    //根据token和did请求数据列表,从json中获取头像url
    let str = "https://api.weibo.com/2/users/show.json"
    let paras = ["access_token":token2,"uid":userId2] 
    Alamofire.request(.GET, str, parameters: paras, encoding: .URL, headers: nil).responseJSON { response in
        let JSON = response.result.value
        let str = JSON?.objectForKey("profile_image_url") as! String
        print("profile_image_url = \(str)")
    }
}

这边使用了Alamfire,(也就是oc中大名鼎鼎的AFNetworking,同一个作者)发送请求,并解析了JOSN数据 接下来就可以各种请求数据,保存数据了。

收藏
0
sina weixin mail 回到顶部