ios开发的时候,由于初学,所以感觉在第三方库导入的时候存在着很大的问题。搞来搞去不知道搞了多久才成功导入,以下就来分析下,作为初学者的我在使用这个框架(刚导入成功而已,谈不上使用)遇到了哪些问题:
刚开始使用了手动拖入的方式将下载下来的文件导入,显然不行 存在着许多的问题,所以采取正规的方法,使用cocoapods插件导入,安装这个插件之前要确保系统已经安装了rvm和ruby这两个东西(具体如何安装百度下就可以了)。我的问题出在了cocoapods安装之后的导入过程中,首先在终端$cd <工程的所在路径>(注意,这里是根目录,目录不要搞错了) 接着 $touch Podfile 然后 $open -e -Podfile 编辑这个文件 platform :'ios','8.0' pod 'AFNetworking' ,'~>2.0.0' 这里的版本要跟xcode的对应不然导进去会出现很多错误。最后 $pod install (这个命令之前要把工程关闭完) 就算完成了。 导入成功后打开目录下面的.xcworkspace就可以了。
以下是网上的一些网络请求代码:
如何通过URL获取json数据
第一种,利用
AFJSONRequestOperation,
官方网站上给的例子:
NSString *str=[NSString stringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 从URL获取json数据
AFJSONRequestOperation *operation1 = [AFJSONRequestOperation JSONRequestOperationWithRequest:requestsuccess:^(NSURLRequest *request, NSHTTPURLResponse *response, NSDictionary* JSON) {
NSLog(@"获取到的数据为:%@",JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id data) {
NSLog(@"发生错误!%@",error);
}];
[operation1 start];
第二种方法,利用AFHTTPRequestOperation 先获取到字符串形式的数据,然后转换成json格式,将NSString格式的数据转换成json数据,利用IOS5自带的json解析方法:
NSString *str=[NSString stringWithFormat:@"https://alpha-api.app.net/stream/0/posts/stream/global"];
NSURL *url = [NSURL URLWithString:[str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *html = operation.responseString;
NSData* data=[html dataUsingEncoding:NSUTF8StringEncoding];
id dict=[NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"获取到的数据为: