![]() 2.7℃ 晴 |
|
风向风速:东北风2级 |
|
相对湿度:43% |
|
空气质量:66良 |
Object-C(ios)语言调用天气查询接口示例:
//
// ViewController.m
// ApiTest
//
// Created by administrator on 16/9/8.
// Copyright © 2016年 star. All rights reserved.
//
#import "ViewController.h"
#define Host @"https://api.ip138.com/weather/"
@interface ViewController ()<NSXMLParserDelegate>
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NSString * token = @"859476648b3de65d7680494506dd1a1c6a";
[self executeNetworkWithWeather:@"120112" type:@"1" callBack:@"" token:token];
}
/**
*示例https://api.ip138.com/weather/?code=120112&type=1&callback=&token=859476648b3de65d7680494506dd1a1c6a
*参数说明:
*1. code string 区划代码
*2. type string 1|7(可选,默认为1)
*3. callback string 回调函数 当前参数仅为jsonp格式数据提供(可选,默认为空)
*4. token string 购买服务后会提供(必填)
*/
- (void)executeNetworkWithWeather:(NSString *)code type:(NSString *)type callBack:(NSString *)callBack token:(NSString *)token{
NSString * urlString =[NSString stringWithFormat:@"%@?code=%@&type=%@&callback=%@&token=%@",Host,code,type,callBack,token];
//准备网络请求
NSString *newStr = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:newStr];
NSURLRequest *requst = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10];
//请求异步链接
[NSURLConnection sendAsynchronousRequest:requst queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError) {
NSLog(@"jsonError = %@",connectionError);
return ;
}
//请求格式txt
if ([dateType isEqualToString:@"txt"]) {
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"result = %@",result);
}
//datatype xml
else if ([dateType isEqualToString:@"xml"]){
NSString *result = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"result = %@",result);
}
else{
NSError *jsonError = nil;
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
/*如果设置了回调函数,则可截取后再在转化为NSDictionary,也可直接转化为NSString*/
if (callBack&&[callBack length]>0) {
NSRange range = [jsonString rangeOfString:@"("];
range.location++;
range.length = [jsonString length] - range.location - 1;
jsonString = [jsonString substringWithRange:range ];
}
NSDictionary *jsonResponse =
[NSJSONSerialization JSONObjectWithData:[jsonString dataUsingEncoding:NSUTF8StringEncoding]
options:0
error:&jsonError];
if (jsonError) {
NSLog(@"jsonError = %@",jsonError);
return ;
}
NSLog(@"jsonResponse = %@",jsonResponse);
}
}];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end