【发布时间】:2014-01-01 07:09:38
【问题描述】:
这是我第一次尝试在 iOS 中使用 PHP 脚本检索网络数据。我在www.mobilenicity.com/test.php 有一个简单的php 脚本,它简单地呼应了“成功”这个词。我的目的是能够检索此文本并通过 NSLog 命令输出它。
目前,我正在使用 iOS 模拟器,但我不确定这是否会产生我需要处理的任何问题。我可以使用模拟器通过 Safari 访问网页,所以我知道那里有连接。
我已经盯着这个看了很长一段时间,但我不知道我哪里出错了。这就是我所拥有的。 NSLog 输出是“下载无效”。我通过使用另一个NSLog 知道我在didFailWithError 方法中失败了。不幸的是,我不知道如何获取 NSNotificationCenter 的输出。
任何人都可以看到问题吗?谢谢!
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *s = @"http://wwww.mobilenicity.com/test.php";
NSURL *url = [NSURL URLWithString:s];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
MyDownloader *d = [[MyDownloader alloc] initWithRequest:req];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(finished:)
name:@"connectionFinished"
object:d];
[d.connection start];
}
- (void) finished: (NSNotification *) n
{
MyDownloader *d = [n object];
NSData *data = nil;
if ([n userInfo]) {
NSLog(@"download didn't work");
} else {
data = d.receivedData;
NSLog(@"%@", data);
}
[[NSNotificationCenter defaultCenter] removeObserver:self
name: @"connectionFinished"
object:d];
}
MyDownloader.h
#import <Foundation/Foundation.h>
@interface MyDownloader : NSObject
@property (nonatomic, strong, readonly) NSURLConnection *connection;
@property (nonatomic, strong, readonly) NSData *receivedData;
- (id) initWithRequest: (NSURLRequest *) req;
- (void) cancel;
@end
MyDownloader.m
#import "MyDownloader.h"
@interface MyDownloader()
@property (nonatomic, strong, readwrite) NSURLConnection *connection;
@property (nonatomic, copy, readwrite) NSURLRequest *request;
@property (nonatomic, strong, readwrite) NSMutableData *mutableReceivedData;
@end
@implementation MyDownloader
- (NSData *) receivedData
{
return [self.mutableReceivedData copy];
}
- (id) initWithRequest:(NSURLRequest *)req
{
self = [super init];
if (self) {
self->_request = [req copy];
self->_connection =
[[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:NO];
self->_mutableReceivedData = [NSMutableData new];
}
return self;
}
- (void) connection:(NSURLConnection *) connection didReceiveResponse:(NSURLResponse *)response
{
[self.mutableReceivedData setLength:0];
}
- (void) connection:(NSURLConnection *) connection didReceiveData:(NSData *)data
{
[self.mutableReceivedData appendData:data];
}
- (void) connection:(NSURLConnection *) connection didFailWithError:(NSError *)error
{
[[NSNotificationCenter defaultCenter]
postNotificationName:@"connectionFinished"
object:self userInfo:@{@"error":error}];
}
- (void) connectionDidFinishLoading:(NSURLConnection *) connection
{
[[NSNotificationCenter defaultCenter]
postNotificationName:@"connectionFinished" object:self];
}
- (void) cancel
{
// cancel download in progress, replace connection, start over
[self.connection cancel];
self->_connection =
[[NSURLConnection alloc] initWithRequest:self->_request delegate:self startImmediately:NO];
}
@end
【问题讨论】:
-
究竟发生了什么是?
-
哦,对不起。我会把它添加到我的帖子中。我的错。
标签: php ios objective-c httprequest