我有服务器中的json文件与休息APLI,我想与服务器通信,现在我用这种方法连接到服务器,并在我的viewdidload方法中调用它,我的问题是什么是最好的方式来做到这一点,我可以使用单身?如果是的话它应该是什么样子?提前致谢!iOS - 通过单例实现连接到服务器
欣赏答案部分中的任何代码建议。
- (void)viewDidLoad
{
[super viewDidLoad];
_mapView.showsUserLocation = YES;
_mapView.delegate = self;
[self fetchData];
}
-(void)fetchData
{
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:BASED_URL]];
[request setHTTPMethod:@"GET"];
[request setValue:@"/json;charset=UTF-8" forHTTPHeaderField:@"Content-Type"];
NSURLResponse *response;
NSData *GETReply = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:nil];
NSString *theReply = [[NSString alloc] initWithBytes:[GETReply bytes] length:[GETReply
length] encoding: NSASCIIStringEncoding];
CLLocationCoordinate2D location;
NSMutableArray *newAnnotations = [NSMutableArray array];
NSError *error;
NSArray *array = [NSJSONSerialization JSONObjectWithData:GETReply
options:0
error:&error];
if (error != nil)
{
// handle the error
}
for (NSDictionary *dictionary in array)
{
location.latitude = [dictionary[@"latitude"] doubleValue];
location.longitude = [dictionary[@"longitude"] doubleValue];
// create the annotation
MyAnnotation *newAnnotation;
newAnnotation = [[MyAnnotation alloc] init];
newAnnotation.company = dictionary[@"company"];
newAnnotation.coordinate = location;
[newAnnotations addObject:newAnnotation];
}
[self.mapView addAnnotations:newAnnotations];
}
更新:根据意见辛格尔顿是没有必要做网络功能和它的不建议做。
我怎样才能提高这些代码,感激,如果你可以给我的解决方案提高了代码
'Singleton'用于在应用程序中创建单个实例。在Network活动的情况下,建议不要使用Singleton,因为您可能需要同时创建多个网络连接,但它不起作用。你可以选择静态函数,也可以选择一些像AFNetworking这样的好的库来减少你的代码。 – iphonic
@iphonic谢谢您的评论,请给我一个例子,我可以如何改进我的代码?(请给我一个基于我的代码的例子)我很感激,如果你把它写在回答部分,那么其他人也可以使用它,谢谢 –