
[英]How to connect to MEAN stack REST api using swift 3 for iOS
[英]NSUrlConnection to connect REST API - XCode 4.2 targetting iOS4 and iOS 5
我正在开发一个使用XCode 4.2以iOS4为目标的应用程序。 从来没有做过,这是我开发iPhone应用程序的第一个月。
我做了一些研究,并且进行了ASIHTTPRequest - 它没有被维护,甚至开发人员建议使用其他东西: http ://allseeing-i.com/%5Brequest_release%5D;
从那个列表中,我想为什么不使用NSUrlConnection,因为它是在XCode中构建的。 我知道RESTKit在那里看起来很受欢迎,但我听说设置有点麻烦 - 我不需要任何花哨的东西,只需连接到返回JSON的REST API服务,所以我觉得NSURLConnection绰绰有余。
不太清楚如何做到这一点,特别是因为我的目标是iOS4和iOS5,而据我所知,iOS 5 SDK引入了NSURLConnectionDelegate(不确定它们有多么不同?)。
我最初关注这篇文章https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html 。 但我有一些疑问,因为它显然在顶部说:MAC OSX Developer Library而不是iOS Developer Library。
谁能指出我正确的方向? 任何示例或教程?
我找到了类似的文章,但是对于iOS Developer Library(不是MAX OSX),它们都非常相似(或者可能具有相同的内容)。 https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE这就是我最后所做的而不是实现NSURLConnectionDelegate。
在本教程之后结合JSONKit: http : //www.techtraits.com/jsonkit/为我完成了这项工作。
需要注意的一点是:我必须关闭ARC,因为JSONKit目前不支持它。
例子:
- (IBAction)callRest:(id)sender {
NSURL *url = [NSURL URLWithString:@"http://www.example.com/Person/123"];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
if(connection) {
responseData = [[NSMutableData alloc] init];
} else {
NSLog(@"connection failed");
}
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
JSONDecoder *decoder = [[JSONDecoder alloc] initWithParseOptions:JKParseOptionNone];
NSDictionary* json = [decoder objectWithData:responseData];
if(json != nil)
{
NSLog(@"First Name %@", [json objectForKey:@"FirstName"]);
NSLog(@"Last Name %@", [json objectForKey:@"LastName"]);
}
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[connection release];
[responseData release];
NSLog(@"connection error");
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connection success");
}
另外,我必须在.h文件中声明响应数据
@property (retain, nonatomic) NSMutableData *responseData;
在.m文件中:
@synthesize responseData;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.