转载

在 Swift 中使用 API(JSON、NSData)

这是一篇关于在 Swift 下通过 API 获取数据的学习笔记,如有错误纰漏欢迎评论指出,感谢。

什么是API?

记得刚开始学习iOS开发时就接触过这个字眼,遂 Google 得到以下解释:

应用程序接口(英语:Application Programming Interface,简称:API),又称为应用编程接口,就是软件系统不同组成部分衔接的约定。由于近年来软件的规模日益庞大,常常需要把复杂的系统划分成小的组成部分,编程接口的设计十分重要。程序设计的实践中,编程接口的设计首先要使软件系统的职责得到合理划分。良好的接口设计可以降低系统各部分的相互依赖,提高组成单元的内聚性,降低组成单元间的耦合程度,从而提高系统的维护性和扩展性。- 摘自维基百科

毫无疑问看得一知半解。简而言之,API的用途就是接入数据的通道,比如你想开发一个读书类的 App,需要图书信息资源,这时候就可以找到豆瓣提供的 API 来接入获取数据。

通过平台提供的 API 获取 JSON

这里拿白宫的 请愿书 API 为例,通过提供的 API 请求到下方的 JSON 数据(示例)。JSON,可以理解为一种描述数据的文本格式,

在 Swift 中使用 API(JSON、NSData)

SwiftyJSON

SwiftyJSON 是一个可以让解析 JSON 数据变得异常方便的第三方库,详细内容可以点击转跳到 Github 页查看。

确认状态

//通过平台提供的 API 链接创建一个 String  let urlString = "https://api.whitehouse.gov/v1/petitions.json?limit=100" //创建 NSData 对象    if let url = NSURL(string: urlString) {       if let data = try? NSData(contentsOfURL: url, options: []) {       //导入SwiftyJSON,传入NSData 创建 JSON 对象          let json = JSON(data: data) //通过 SwiftyJSON 便利地「一层层剥开」拿到数据   if json["metadata"]["responseInfo"]["status"].intValue == 200 {             // 确认状态后就可以开始解析JSON          }       }    } 

获取状态指的是解析 JSON 拿到"status"的值,当 status 的值为"200"时,意为「一切正常」。根据白宫请愿开发者页面所示,例如服务器异常引发的获取失败,那么 status 的值将会是"599",从而可以让我们对不同的情况做出不同的响应。

获取数据

上面「确认状态」的片段其实已经涉及到了获取数据。我们可以查看平台提供的JSON返回数据实例来查看各个数据的嵌套方式和各个数据的「title」:

{   "metadata": {     "responseInfo": {       "status": 200,       "developerMessage": "OK",       "userMessage": "",       "errorCode": "",       "moreInfo": ""     },     "requestInfo": {       "apiVersion": 1,       "resource": "petitions",       "query": {         "body": null,         "createdAfter": null,         "createdAt": null,         "createdBefore": "1352924535",         "isPublic": 1,         "isSignable": null,         "limit": "3",         "mock": 0,         "offset": "0",         "petitionsDefaultLimit": 1000,         "publicThreshold": 149,         "responseId": null,         "signatureCount": null,         "signatureCountCeiling": null,         "signatureCountFloor": 0,         "signatureThreshold": null,         "signatureThresholdCeiling": null,         "signatureThresholdFloor": null,         "status": null,         "title": null,         "url": null,         "websiteUrl": "https://petitions.whitehouse.gov"       }     },     "resultset": {       "count": 809,       "limit": 3,       "offset": 0     }   },   "results": [     {       "id": "226511",       "type": "petition",       "title": "Ban the practice of circumcising individuals under the age of 18.",       "body": "Circumcision is a barbaric tribal practice that amounts to child abuse. Before any individual under go any permanent body modification such as tattooing or sex reassignment surgery they must be considered old enough to understand the consequences. You cannot understand the ramifications of this act to your physical being until after puberty, when your genitals have fully developed. ",       "issues": [         {           "id": 4,           "name": "Civil Rights and Liberties"         },         {           "id": 25,           "name": "Health Care"         },         {           "id": 28,           "name": "Human Rights"         }       ],       "signatureThreshold": 25000,       "signatureCount": 3085,       "signaturesNeeded": 21915,       "url": "https://petitions.whitehouse.gov/petition/ban-practice-circumcising-individuals-under-age-18",       "deadline": 1355512735,       "status": "closed",       "response": [     ],       "created": 1352920735,       "isSignable": false,       "isPublic": true     },     {       "id": "224306",       "type": "petition",       "title": "Remove HEMP (Non-Psychoactive Cannabis) from the Federal governments banned substance list. Make it Legal to Grow in USA",       "body": "There is no reason for it to be illegal. It won't make you high. It is Not Marijuana, and it alone could make enough oil to free the nation. Hemp is the most versatile plant in the Universe, its strong enough to make rope, and diverse enough to make oil. This plant will grow almost everywhere with very little maintenance and without watering.And it is insect resistant naturally. It grows quickly and the steps to turn it into gasoline are very simple. We could replace our need for anything other than hemp in a matter of Months, not years./r/n/r/nFuel:/r/n/r/n* Hemp can produce 10 times more methanol than corn. /r/n* Hemp is Earth's number-one biomass resource; it is capable of producing 10 tons per acre in four months./r/n",       "issues": [         {           "id": 1,           "name": "Agriculture"         },         {           "id": 3,           "name": "Budget and Taxes"         },         {           "id": 20,           "name": "Environment"         }       ],       "signatureThreshold": 25000,       "signatureCount": 5091,       "signaturesNeeded": 19909,       "url": "https://petitions.whitehouse.gov/petition/remove-hemp-non-psychoactive-cannabis-federal-governments-banned-substance-list-make-it",       "deadline": 1355510348,       "status": "closed",       "response": [     ],       "created": 1352918348,       "isSignable": false,       "isPublic": true     },     {       "id": "224016",       "type": "petition",       "title": "Stop the US Diversity Immigrant Visa (Lottery) Program - /"The USA's Open Door Welfare Program/"...",       "body": "Millions of Americans don't realize what's going on in this country./r/nAnyone can fill out an online application form, then /"WIN/" the right to come to this country and claim all the benefits. The LOTTERY makes available up to 55,000 diversity visas annually, drawn from random selection BY COMPUTER; they are just WINNING/" permanent resident status based on no qualifications!/r/nAs a result, government officials are admitting millions of immigrants each year who are dependent on Medicaid, child care benefits, foster care, energy assistance, education assistance, nutritional welfare programs and other medical and health benefits./r/nWe cant afford for our government to promote a policy that encourages immigrants to apply for a green card Lottery and /"WIN/"- NOT DESERVE the right to become USA citizen!",       "issues": [         {           "id": 29,           "name": "Immigration"         }       ],       "signatureThreshold": 25000,       "signatureCount": 2819,       "signaturesNeeded": 22181,       "url": "https://petitions.whitehouse.gov/petition/stop-us-diversity-immigrant-visa-lottery-program-usas-open-door-welfare-program",       "deadline": 1355509876,       "status": "closed",       "response": [     ],       "created": 1352917876,       "isSignable": false,       "isPublic": true     }   ] } 

刚刚我们想要"status"的数据,就通过 SwiftyJSON 的 json[“metadata”][“responseInfo”][“status”].intValue 「剥开」三层拿到数据的 int 值,而"result"数据与"metadata"平级,就可以这么拿到数据:json[“result”]。

根据这个 API 提供的数据,拿到请愿书的 title、body 等数据:

for result in json["results"].arrayValue {         let title = result["title"].stringValue         let body = result["body"].stringValue         let sigs = result["signatureCount"].stringValue         let obj = ["title": title, "body": body, "sigs": sigs]     } 

取得"result"数据的数组值并便利每块"result",进一步从中取出其他数据并根据 key 保存在字典中,这样我们就实现了从平台上获取数据啦。

正文到此结束
Loading...