0

在我的应用程序中,我使用的是一个静态库。在那个库中,我实现了与服务器建立连接的代码。对于我使用的服务器交互,NSURLSession但它延迟了 UI 响应以避免它我已经开始使用NSURLConnection委托方法现在我从服务器获取响应但在这里我不知道如何将响应从完成加载方法发送回实际代码。

在我的团队中,我想将此库分发给 iphone 和 ipad 开发工程师。他们对我在静态库中实现的所有服务器相​​关代码没有任何控制。因此,请提前向我展示我的问题的解决方案,谢谢。

以下是我在一类静态库中使用的代码:

静态类:

.h 文件

@interface StaticClass : NSObject<NSURLConnectionDelegate,NSURLSessionDelegate>

{
NSMutableDictionary  *responseDictionary;
NSUserDefaults *serviceURlInUserDefaults;
NSData *responseData;

}
@property (nonatomic, weak) id <DataReciverDelegate>delegate;
@property(strong,nonatomic)NSData *responseData;


-(void)loginWithUsername:(NSString *)name password:(NSString*)password serviceUrl:(NSString*)serviceUrl domainName:(NSString*)domainName ;


@end

导入“静态类.h”

@protocol DataReciverDelegate <NSObject>

@required
- (void)responseDictionary:(NSDictionary *)response;

@end


@implementation StaticClass
@synthesize responseData;


-(void)loginWithUsername:(NSString *)name password:(NSString*)password serviceUrl:(NSString*)serviceUrl domainName:(NSString*)domainName 
{

 NSString *ApiStr=[NSString stringWithFormat:@“http://login.com”];

    NSURL *Url=[[NSURL alloc]initWithString:[loginApiStr stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];

   NSURLRequest *ApiRequest=[NSURLRequest requestWithURL:loginUrl];

    NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:ApiRequest delegate:self];
    [connection start];

}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{

}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

    self.responseData=data;

}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{


    responseDictionary=[NSJSONSerialization JSONObjectWithData:self.responseData options:0 error:nil];

    [_delegate responseDictionary:responseDictionary];

}

@end

我想使用的响应在 class1 中:

在这里请让我知道如何包含我在静态库类中创建的委托

@interface Class1 : NSObject<NSURLConnectionDelegate,NSURLSessionDelegate>

{

}

@end

@implementation Class1


-(void)login
{
StaticClass *object1=[[StaticClass alloc]init];

[object loginWithUsername:@“AAA” password:@“BBB” serviceUrl:url domainName:dname];

}
4

2 回答 2

1

您可以提供 API 来通知已从连接中读取响应,也可以发送通知。

第一个可以通过实现委托协议并在使用应用程序中设置委托,或者通过使用基于块的 API 来完成,其中使用应用程序将设置一个块来处理事件。您在系统提供的 API 中经常看到这两种模式,包括NSUrlConnection.

另一种选择是使用通知。您在使用的应用程序中注册特定的通知名称,并在您的连接返回数据后发布的库中。

于 2014-02-12T06:48:43.673 回答
1

您需要在静态库中实现一个协议,例如:

@protocol DataReciverDelegate <NSObject>

@required
- (void)dataReceived:(NSData *)data;

@end

还在那里声明一个属性,例如:

@property (nonatomic, weak) id <DataReciverDelegate>delegate;

在您的静态库实现中,实现connectionDidFinishLoading类似:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
   [_delegate dataReceived:_dataYouReceived];
}

现在你需要DataReciverDelegate在你需要获取数据的类中实现,当你创建静态库类的对象时,设置委托。

于 2014-02-12T06:49:48.013 回答