2014-07-22 28 views
1

我有服务器中的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]; 
} 

更新:根据意见辛格尔顿是没有必要做网络功能和它的不建议做。

我怎样才能提高这些代码,感激,如果你可以给我的解决方案提高了代码

+0

'Singleton'用于在应用程序中创建单个实例。在Network活动的情况下,建议不要使用Singleton,因为您可能需要同时创建多个网络连接,但它不起作用。你可以选择静态函数,也可以选择一些像AFNetworking这样的好的库来减少你的代码。 – iphonic

+0

@iphonic谢谢您的评论,请给我一个例子,我可以如何改进我的代码?(请给我一个基于我的代码的例子)我很感激,如果你把它写在回答部分,那么其他人也可以使用它,谢谢 –

回答

6

根据我的评论。

Singleton用于通过应用程序创建单个实例。在Network活动的情况下,建议不要使用Singleton,因为您可能需要同时创建多个网络连接,但它不起作用。您可以选择静态函数,并使用一些好的库,如AFNetworking来减少代码。而且,您应该使用网络活动asynchronous而不是synchronous,因为如果需要时间来获取数据,它将会使用block app activity

要修改您的代码,您可以按照下面的代码。

创建一个ApiManager类,将完成所有的网络活动,把所有你在类代码..见下面

ApiManager.h

进口

@interface ApiManager : NSObject 
+(void)fetchCoordinates:(void (^) (id result))success failure:(void (^) (NSError *error))failure; 
@end 

ApiManager.m

#import "ApiManager.h" 

#define BASED_URL @"" 


@implementation ApiManager 
+(void)fetchCoordinates:(void (^) (id result))success failure:(void (^) (NSError *error))failure{ 
    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]; 

    NSError *error; 
    NSArray *array = [NSJSONSerialization JSONObjectWithData:GETReply 
                options:0 
                 error:&error]; 

    if(!error){ 
     success(array); 
    }else 
     failure(error); 

} 
@end 

Usage

[ApiManager fetchCoordinates:^(id result) { 

    NSArray *array=(NSArray*)result; 

    NSMutableArray *newAnnotations = [NSMutableArray array]; 

    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]; 
} failure:^(NSError *error) { 

}]; 

希望它能帮助。

干杯。

+0

非常感谢,我应该在哪里添加此部分? for(NSDictionary * dictionary in array) { location.latitude = [dictionary [@“latitude”] doubleValue]; location.longitude = [字典[@“longitude”] doubleValue]; //创建注释 MyAnnotation * newAnnotation; newAnnotation = [[MyAnnotation alloc] init]; newAnnotation.company = dictionary [@“company”]; –

+0

@SaraShumika更新了答案.. – iphonic

0
  • 辛格尔顿是没有必要做网络功能和它的不建议做。
  • 在调用网络API时,您可能需要执行多线程操作
  • AFNetworking是一个很好的库,可以查看和利用您的朋友的网络相关代码。它的积极发展,也有一个良好的用户群体。
+0

改变你的第二点:“如果你在调用网络API时没有使用多线程,你的客户会仇恨你”。 – gnasher729

+0

我感到困惑的是'AFNetworking'文档实际上建议使用单例:“鼓励针对iOS 7或Mac OS X 10.9或更高版本开发者广泛处理Web服务的开发人员为'AFHTTPSessionManager'创建子类,提供一个类方法,该方法返回可以在整个应用程序之间共享认证和其他配置的共享单例对象。“ (请参阅:http://cocoadocs.org/docsets/AFNetworking/2.3.1/Classes/AFHTTPSessionManager.html)。这是否定义规则的例外? – Koen

+0

即使Apple使用Singleton作为网络管理器类:https://developer.apple.com/library/ios/samplecode/MVCNetworking/Listings/Networking_NetworkManager_h.html – Koen