讓我們正在進行的一步:
1)你要使用,使API調用框架NSURLSession(或類似Alomofire一些圖書館等)。
一個例子調用API:
func getBooksData(){
let url = "http://de-coding-test.s3.amazonaws.com/books.json"
(NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
//Here we're converting the JSON to an NSArray
if let jsonData = (try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves)) as? NSArray{
//Create a local variable to save the data that we receive
var results:[Book] = []
for bookDict in jsonData where bookDict is NSDictionary{
//Create book objects and add to the array of results
let book = Book.objectWithDictionary(bookDict as! NSDictionary)
results.append(book)
}
dispatch_async(dispatch_get_main_queue(), {() -> Void in
//Make a call to the UI on the main queue
self.books = results
self.tblBooks.reloadData()
})
}
}).resume()
}
Book實體:
class Book{
var title:String
init(title:String){
self.title = title
}
class func objectWithDictionary(dict:NSDictionary)->Book{
var title = ""
if let titleTmp = dict.objectForKey("title") as? String{
title = titleTmp
}
return Book(title: title)
}
}
注:在實踐中,您將檢查錯誤和響應的狀態代碼,你也可以提取將API調用給另一個類(或服務層)的代碼。一種選擇,使用DataMapper模式,您可以通過實體創建一個類管理器(在本例中爲書籍管理器BookManager),您可以製作類似你可以抽象e VEN更多,創建一個通用的API,即收到一個網址,並從JSON改造返回AnyObject,並從你的經理裏面就有進程):
class BookManager{
let sharedInstance:BookManager = BookManager()
private init(){}
func getBookData(success:([Book])->Void,failure:(String)->Void){
let url = "http://de-coding-test.s3.amazonaws.com/books.json"
(NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!) { (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
if error != nil{
failure(error!.localizedDescription)
}else{
if let jsonData = (try? NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves)) as? NSArray{
var results:[Book] = []
for bookDict in jsonData where bookDict is NSDictionary{
let book = Book.objectWithDictionary(bookDict as! NSDictionary)
results.append(book)
}
success(results)
}else{
failure("Error Format")
}
}
}).resume()
}
}
你還指望我們回答,到底是什麼? – Alexander
試試這個庫並檢查示例:https://github.com/Alamofire/Alamofire – derdida