自分のアプリケーションの 1 つに対して同じことを行った方法を次に示します。
*注: これは、POST 要求ではなく GET 要求を実行しますが、バックグラウンドで実行され、効率的に実行されます
サーバーからデータを取得するためのクラスを作成します (私は online.h/m と呼びます)
AppDelegate.h
//
// AppDelegate.h
// Faith Life Fellowship Streamer
//
// Created by David Worth on 7/17/11.
// Copyright 2011 Math Nerd Productions, LLC. All rights reserved.
//
#import <UIKit/UIKit.h>
@class ViewController;
@interface AppDelegate : NSObject <UIApplicationDelegate> {
NSOperationQueue *queue;
}
@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet ViewController *viewController;
@property (nonatomic, retain) NSString *receivedURL;
- (void)stringLoad:(NSString*)str;
+ (id)shared;
- (void)addOperation:(NSOperation*)operation;
@end
これらのピースを AppDelegate.m に追加します
@synthesize receivedURL;
static AppDelegate *shared;
+ (id)shared;
{
if (!shared) {
[[AppDelegate alloc] init];
}
return shared;
}
- (id)init
{
if (shared) {
[self autorelease];
return shared;
}
if (![super init]) return nil;
queue = [[NSOperationQueue alloc] init];
shared = self;
return self;
}
- (void)addOperation:(NSOperation *)operation
{
[queue addOperation:operation];
}
- (void)stringLoad:(NSString *)str
{
self.receivedURL = str;
[[NSNotificationCenter defaultCenter] postNotificationName:@"string" object:nil];
}
online.h
//
// online.h
// FLF Streamer
//
// Created by David Worth on 4/30/12.
// Copyright (c) 2012 Math Nerd Productions, LLC. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "AppDelegate.h"
@interface online : NSOperation
@property (nonatomic, retain) NSString* str;
@property (nonatomic) int type;
- (id)initWithString:(NSString*)url;
@end
online.m
//
// online.m
// FLF Streamer
//
// Created by David Worth on 4/30/12.
// Copyright (c) 2012 Math Nerd Productions, LLC. All rights reserved.
//
#import "online.h"
@implementation online
@synthesize str;
- (id)initWithString:(NSString *)url
{
if (![super init]) return nil;
[self setStr:url];
return self;
}
- (void)dealloc {
[str release], str = nil;
[super dealloc];
}
- (void)main {
NSString *webpageString = [[[NSString alloc] initWithContentsOfURL:[NSURL URLWithString:str] encoding:NSUTF8StringEncoding error:nil] autorelease];
[[AppDelegate shared] performSelectorOnMainThread:@selector(stringLoad:)
withObject:webpageString
waitUntilDone:YES];
}
@end
次に、viewcontroller.mで呼び出します ( mysite.com... をアクセスしたい PHP ページの URL に置き換えます):
online* o = [[online alloc] initWithString:@"http://www.mysite.com/myphppage.php?variable1=blah+blah+blah"];
AppDelegate* delegate = [AppDelegate shared];
[delegate addOperation:o];
そして、あなたのviewcontroller.m viewDidLoad メソッドで:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(myMethodToProcessWhatTheServerReturns) name:@"string" object:nil];
そして、サーバーが返すものを解析するメソッドを viewController.m に作成します。
- (void)myMethodToProcessWhatTheServerReturns
{
NSString* serverResponse = [AppDelegate shared].receivedURL;
//Do stuff with serverResponse
}
ハッピーコーディング!