感谢您的帮助,如果别人需要一个解决方案,这是我的代码:
.h文件中:
@interface WelcomeViewController : UIViewController <NSURLConnectionDelegate>
{
NSMutableData *_responseData;
}
.m文件:
-(void)postToDataBaseWithName:(NSString*)nameToPost andEmail:(NSString*)emailToPost {
NSString *str = [NSString stringWithFormat:@"http://website.com/users/save.php?save={\"email\":\"%@\",\"name\":\"%@\"}", emailToPost, nameToPost];
str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:str];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// Create url connection and fire request
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn) {
}
}
也增加委托方法,看看它是如何工作的:
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
NSLog(@"didReceiveResponse");
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
NSLog(@"didReceiveData");
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
NSLog(@"connectionDidFinishLoading");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// The request has failed for some reason!
// Check the error var
NSLog(@"didFailWithError = %@", error);
}
Vicor作为初学者,请尽可能的解释你的问题。我想你要求将数据从应用程序发布到服务器。如果是,那么请在服务器上创建发布请求并发送数据。看看以下链接https://www.raywenderlich.com/67081/cookbook-using-nsurlsession http://stackoverflow.com/questions/19099448/send-post-request-using-nsurlsession http://stackoverflow.com/questions/34327919/post-request-with-raw-body-using-nsurlsession https://developer.apple.com/reference/foundation/urlsession –
你的问题含糊不清。你是说你想用GET请求从服务器下载数据,然后在本地保存这些数据?或者你是否说你有要发送到服务器的数据?您的网址看起来像您正试图将JSON放在网址中。你不能那样做。您可以使用查询字符串来设置少量的键值对,但无法以这种方式提供JSON有效内容。如果您要将数据发送到要使用POST的服务器,而不是GET。 –
亲爱的邓肯C,是的,我试图上传json数据到服务器,实际上是txt文件。我也很困惑。我添加了php文件,如果我只是在web浏览器中打开链接,它会很好用,但是如何在objectve-c中完成呢?谢谢 – Victor