使用swift进行API调用

时间:2016-06-10 21:27:07

标签: swift api

在iOS编码方面,我是一个完全的NOOB。 我正在尝试学习如何对" http://de-coding-test.s3.amazonaws.com/books.json"进行API调用。 但是,由于我是一个完整的菜鸟,所以我找到的所有教程都没有意义如何去做。 我想学习的是如何从Web获取JSON数据并将其输入到UITableViewCell

我已经浏览了大约3打教程,没有任何意义。

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

让我们一步一步:

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()
}

图书实体:

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这样的书),你可以做这样的事情(你可以抽象更多,创建一个通用的api,接收一个url并从中返回一个AnyObject) JSON的转换,以及经理内部的流程):

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()

    }

}