NSJSONSerialization
蘋果官方給出的解析方式是性能最優越的,雖然用起來稍顯復雜。
首先我們在上面已經有了我希望得到的信息的網站的API給我們的URL,在OC中,我要加載一個NSURL對象,來向網站提交一個Request。到這里需要特別注意了,iOS9的時代已經來臨,我們先前在舊版本中使用的某些類或者方法都已經被蘋果官方棄用了。剛剛我們向網站提交了一個Request,在以往,我們是通過NSURLConnection中的sendSynchronousRequest方法來接受網站返回的Response的,但是在iOS9中,它已經不再使用了。從官方文檔中,我們追根溯源,找到了它的替代品——NSURLSession類。這個類是iOS7中新的網絡接口,蘋果力推之,並且現在用它完全替代了NSURLConnection。關於它的具體用法,還是蠻簡單的,直接上代碼(ViewController.m文件):
#import "ViewController.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UITextView *textView;
@property (nonatomic, strong) NSMutableDictionary *dic;
@property (nonatomic, strong) NSString *text;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (IBAction)didClickNSJsonButton:(id)sender {
//GCD異步實現
dispatch_queue_t q1 = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(q1, ^{
NSURL *url = [NSURL URLWithString:@"https://api.douban.com/v2/movie/subject/25881786"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//使用NSURLSession獲取網絡返回的Json並處理
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
self.dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSString *title = [self.dic objectForKey:@"original_title"];
NSMutableArray *genresArray = [self.dic objectForKey:@"genres"];
NSString *genres = [NSString stringWithFormat:@"%@/%@",[genresArray objectAtIndex:0],[genresArray objectAtIndex:1]];
NSString *summary = [self.dic objectForKey:@"summary"];
self.text = [NSString stringWithFormat:@"電影名稱:%@\n體裁:%@\n劇情介紹:%@",title,genres,summary];
//更新UI操作需要在主線程
dispatch_async(dispatch_get_main_queue(), ^{
self.textView.text = self.text;
});
}];
[task resume];
});
}
有時候我們在使用第三方網絡訪問包的時候,導入的時候會出現一堆錯誤,這可能是因為它不支持ARC,這時候不用慌,我們會發現大部分是ARC的問題,解決方法也挺簡單,我們進入項目的Target,找到Build Phases里面的Compile Sources,接着找我們的問題源頭*.m文件,雙擊更改它的Compiler Flags標簽為“-fno-objc-arc”,再次編譯,就好啦~
