初次学习IOS 网络请求
在AppDelegate.m中
#import "AppDelegate.h"
#import "MainViewController.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
//调用
run();
self.viewController = [[MainViewController alloc] init];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
//定义一个函数中网络请求
void run(){
NSURL *url = [NSURL URLWithString:@"https://api.map.baidu.com/place/v2/search?query=%E9%93%B6%E8%A1%8C®ion=%E9%83%91%E5%B7%9E&output=json&ak=6E823f587c95f0148c19993539b99295"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
[request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET
//设置参数
NSString *str = @"query=%E9%93%B6%E8%A1%8C®ion=%E9%83%91%E5%B7%9E&output=json&ak=6E823f587c95f0148c19993539b99295";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
//第三步,连接服务器
NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *str = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
NSLog(@"%@",str);
// 弹出数据
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"title" message:str delegate:@"" cancelButtonTitle:@"cancel" otherButtonTitles:@"confirm", nil];
[alert show];
}
@end