前面大概介紹了react-native的運行helloword級別的入門,所以之后簡單的東西就不寫了,畢竟官網上都能夠找到。
reactnative官網:https://facebook.github.io/react-native/docs/getting-started.html
reactnative中文網:http://reactnative.cn/docs/0.25/getting-started.html
之后我會把工作中遇到的一些react-native的深坑分享一下。
正題===========================
客戶端cookies的獲取就是一個大坑。
1.使用三方
研究ReactNative的源碼發現,框架中並沒有實現iOS的NSHTTPCookieStorage的api,所以搜遍百度谷歌和bing,最終找到了一個哥們寫的第三方cookies工具:
https://github.com/joeferraro/react-native-cookies
這里需要一提的是,我需要取得cookie不僅是dictionary形式的cookies,而是用於http請求的cookiesHeader(比較特殊),其格式是string,在OC中取得的方式是:
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
NSDictionary *header = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
但這一塊原作者的框架中貌似存在一定的問題,所以我寫了一個pull request,具體可以訪問我fork的項目:
https://github.com/rayshen/react-native-cookies
(如果你需要取得的Cookie是用來解析取值或是保存重新加入的,用get("url",res)或者getAll()函數取得的比較適合)
2.獲取當前url
這就需要結合webview控件來進行操作了。
首先我們需要確定當前的url,當前的url可以從webview控件綁定的事件onNavigationStateChange去取得:
onNavigationStateChange={this.onNavigationStateChange.bind(this)}
onNavigationStateChange(navState) { console.log(navState.url); this.curUrl = navState.url; }
3.取得url的cookie header:
CookieManager.getHeader(this.curUrl, (err, res) => { console.log('Got cookies for url: ' + res.Cookie); })
4.取得url的所有cookies
CookieManager.get('http://example.com', (err, res) => { console.log(res); })
5.取得當前所有的cookies
CookieManager.getAll((err, res) => { console.log('cookies!'); console.log(err); console.log(res); });
需要注意的是,getAll()和set()都是iOS Only的函數。