是否可以从AppDelegate.m类为POST调用Web服务(如JSON解析)?我想在应用程序启动时使用Web Service将数据发布到服务器。
#pragma mark JSON Delegates
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
responseData = nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *DictData = (NSDictionary*)[responseString JSONValue];
}
在这里,我附加了示例方法,将其添加到您的AppDelegate.h中
@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
NSURLConnection *clearSession;
NSMutableData * responseData;
}
在您的AppDelegate.m中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self clearsession]; // this is your method Name
return YES;
}
-(void)clearsession
{
// call the clear session
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:@"yourURLName.php"]];
// get the session ID and UserID from Sqlite
NSString *requestString = [NSString stringWithFormat:@"user_id=%@",passyourString,nil];
NSMutableData *requestData =[NSMutableData dataWithBytes:[requestString UTF8String] length: [requestString length]];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: requestData];
clearSession = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[clearSession start];
}
#pragma mark - NSUrlConnectionDelegate Methods
-(void)connection:(NSConnection*)conn didReceiveResponse:(NSURLResponse *)response
{
if (responseData == NULL)
{
responseData = [[NSMutableData alloc] init];
}
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *customAlert = [[UIAlertView alloc]initWithTitle:@"No NetWork" message:@"Interet Connection is Lost" delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
[customAlert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData: responseData options: kNilOptions error:nil];
NSString *str=[jsonDict objectForKey:@"result"];
if ([str isEqualToString:@"success"])
{
// Add your Home Viewcontroller
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"yourIDentifierName"];
self.window.rootViewController=viewController;
}
else
{
// do ur stuff here
}
}
选择二号
使用此链接,这是protocol
方法
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句