ios 怎样获取 本地json数据

ios 怎样获取 本地json数据,第1张

一般获取本地数据是从plist文件中读取JSON数据。

读取数据:

NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"city" ofType:@"plist"]

NSArrary *cityArray = [[NSArray alloc]initWithContentsOfFile:plistPath]

这里的cityArray根据你存在plist中的数据类型来确定,如果plist中是字典类型,那么你这里需要使用NSDictionary去存储你从plist中获取到的数据。

至于本地存储数据的话根据你项目的具体功能来设计,一般的小型数据如用户昵称、手机号等使用NSUserDefault即可,但是如果是大量数据如账单类app中的账单数据那么此时需要考虑使用sqlite3去存储数据,至于密码之类就需要使用NSKeydArchiver去存储。

由于Xcode和MacBook pro经常自己更新,所以我的自己的APP不打算走本地代理了,准备写到本地json

1首先创建路径

//获取文件路径

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"路径名称" ofType:@"json"]

2读取data

//根据文件路径读取数据

NSData *data = [[NSData alloc] initWithContentsOfFile:filePath]

3data专程json

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]

options的几种类型

https://javenl.github.io/ios/2015/06/29/NSJSONSerialization.html

JSON 一般是从网络接口中请求的一段数据吧.首先你要向服务器发送一个请求,得到一段JSON,然后解析一下就行了.用到ASIHTTPRequest和SBJSON两个第三方的开源类库.

NSURL * url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]

sendRequest = [ASIHTTPRequest requestWithURL:url]

[sendRequest setTimeOutSeconds:30]

[sendRequest setDelegate: self]

[sendRequest startAsynchronous]

- (void)requestFinished:(ASIHTTPRequest *)request

{

NSString *responseString = [request responseString]

if (responseString==nil || [responseString JSONValue] == nil) {

return

}

NSDictionary *responseDict = [responseString JSONValue]

int result = [[responseDict objectForKey:@"status"] intValue]

if (result == 1) {

NSArray *location = [responseDict objectForKey:@"locations"]

...............................

}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/sjk/9902273.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-03
下一篇2023-05-03

发表评论

登录后才能评论

评论列表(0条)

    保存