Project 7 Whitehouse Petitions
使用NSURL、NSData
1
2
3
4
5
6
7
8
9
10if let url = NSURL(string: urlString) {
if let data = try? NSData(contentsOfURL: url, options: []) {
let json = JSON(data: data)
if json["metadata"]["responseInfo"]["status"] == 200 {
print("200")
}
}
}使用开源SwiftyJSON,解析JSON字符串
1
2
3
4
5
6
7
8
9
10func parseJSON(json: JSON) {
for result in json["results"].arrayValue {
let title = result["title"].stringValue
let body = result["body"].stringValue
let sigs = result["signatureCount"].stringValue
let object = ["title": title, "body": body, "sigs": sigs]
objects.append(object)
}
tableView.reloadData()
}“NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)”
解决办法:在Info.plist里添加1
2
3
4
5
6
7
8
9
10
11
12
13<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>whitehouse.gov</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>在cellForRowAtIndexPath方法里,显示标题、内容,这里使用默认Cell样式。
1
2cell.textLabel!.text = object["title"]
cell.detailTextLabel!.text = object[“body"]将webView设置为当前view,载入html网页
1
2
3
4
5
6import WebKit
override func loadView() {
webView = WKWebView()
view = webView
}
webView.loadHTMLString(html, baseURL: nil)使用guard保证detailItem不为空,否则返回
1
guard detailItem != nil else { return }
使用当前main的storyboard,代码添加一个TabBar,使用系统默认的tabBarSystemItem
1
2
3
4
5let tabBarController = splitViewController.viewControllers[0] as! UITabBarController
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("NavController") as! UINavigationController
vc.tabBarItem = UITabBarItem(tabBarSystemItem: .TopRated, tag: 1)
tabBarController.viewControllers?.append(vc)判断TabBarItem的标签 navigationController?.tabBarItem.tag == 0
- 有if的地方,记得考虑else的情况。
Project 8 Seven Swifty Words
- 可以取消 Use Size Classes,手动指定一个size
- 默认TextField无法设置高度, that’s because it has a rounded rectangle border around it that must be an exact size. 需要设置borderless
- 将Label的Lines置为0,表示可以有多行
遍历view里面的子view的tag,将button和action建立连接,其中letterTapped: 冒号表示接受一个参数
1
2
3
4
5for subview in view.subviews where subview.tag == 1001 {
let btn = subview as! UIButton
letterButtons.append(btn)
btn.addTarget(self, action: "letterTapped:", forControlEvents: .TouchUpInside)
}使用enumerate进行遍历,使用componentsSeparatedByString字符串分割
1
2
3
4
5
6for(index, line) in lines.enumerate() {
let parts = line.componentsSeparatedByString(": ")
let answer = parts[0]
let clue = parts[1]
..
}字符串替换
1
answer.stringByReplacingOccurrencesOfString("|", withString: “")
字符统计 solutionWord.characters.count
字符串去除空格、换行符
1
clueString.stringByTrimmingCharactersInSet(.whitespaceAndNewlineCharacterSet())
循环 注意 ..< 是一个整体,之间没有空格
1
for i in 0 ..< letterBits.count
获得button的titleLabel,hidden为true表示不可点击
1
2
3btn.titleLabel!.text!
activatedButtons.append(btn)
btn.hidden = true字符串拼接 joinWithSeparator(“\n”)
- 属性观察器 Property Observers,使用didSet
1
2
3
4
5var score = 0 {
didSet {
scoreLabel.text = "Score: \(score)"
}
}
Project 9 Grand Central Dispatch
- 所有的UI工作都在主线程发生,dispatch_get_main_queue获得主线程。
it’s never OK to do user interface work on the background thread. - QoS level set,线程优先级。
- User Interactive
- User Initiated
- The Utility queue
- The Background queue
让代码后台执行,Qos为User Initiated,使用unowned self无主引用,避免强引用。
1
2dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [unowned self] in
在闭包里的方法必须使用self,否则报错Note that because our code is now inside a closure, we need to prefix our method calls with self. otherwise Swift complains.