[[NSString alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"myPHPPathWithParameters"]] encoding:NSUTF8StringEncoding];
在过去获取php作为NSSTRing回应的信息,并且它有效,但现在它没有。它返回一个NULL NSString。无论如何,我认为正确的方法是实现NSURLConnection,因为它实现了用于观察连接进度的委托方法等。所以,我声明了一个静态的NSMutableData * receivedData然后我在iOS文档中使用了这个例子:
NSURLRequest *req=[NSURLRequest
requestWithURL:[NSURL URLWithString:@"http://myphp.php?parameters=paramteres"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
NSURLConnection *con=[[NSURLConnection alloc] initWithRequest:req delegate:self];
if (con)
receivedData = [[NSMutableData data] retain];
else
NSLog(@"Request failed to load.");
然后我实现委托方法(我也在自己声明NSURLConnectionDataDelegate):
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
NSLog(@"RECEIVED DATA;");
[receivedData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"received response;");
[receivedData setLength:0];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"FINISHED;");
}
但这些方法永远不会被调用!终端从不显示任何显示委托方法执行的日志消息。据我所知,调用此方法并将数据附加到receivedData,然后我必须在调用connectionDidFinishLoading方法后从receivedData获取NSString。有什么建议?我也尝试过NSURLConnection中的同步请求类方法,但是这个方法得到了WHOLE HTML,我只想得到php的回声并将其解析为NSString,以便在app中使用:(
答案 0 :(得分:2)
将receivedData
转换为字符串
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *myStringData = [[NSString alloc] initWithData:receivedData encoding:NSStringEncodingConversionAllowLossy];
}
然后打印字符串NSLog(@"MyString: %@", myStringData)