如何从ios中的URL获取数据

时间:2016-05-11 09:21:27

标签: ios

嘿,我是ios的新手,请帮助从这个URL中获取数据...

NSString *urlString = @" http://api.openweathermap.org/data/2.5/forecast/daily?q=Indore&mode=json&units=metric&cnt=10&APPID=fc632e2569dbdbb07ca79e239faa0281";

2 个答案:

答案 0 :(得分:1)

像这样使用NSUrlSession

NSString *urlString = @"http://api.openweathermap.org/data/2.5/forecast/daily?q=Indore&mode=json&units=metric&cnt=10&APPID=fc632e2569dbdbb07ca79e239faa0281";
NSURLSession *session = [NSURLSession sharedSession];
[[session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    // handle the response
}] resume];

答案 1 :(得分:0)

//Init the NSURLSession with a configuration
NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

//Create an URLRequest
NSURL *url = [NSURL URLWithString:@"yourURL"];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];

//Create POST Params and add it to HTTPBody
NSString *params = @"api_key=APIKEY&email=example@example.com&password=password";
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];

//Create task
NSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    //Handle your response here
}];

[dataTask resume];