将数据发布到网址后如何收到响应?

时间:2018-02-05 11:32:22

标签: ios objective-c post

我有这段代码;

NSString *post = [NSString stringWithFormat:@"latitude=%lf&longitude=%lf&provider=network&accuracy=%lf&hiz=%lf&retrieveTime=%@",
                  locationManager.location.coordinate.latitude,
                  locationManager.location.coordinate.longitude,
                  locationManager.location.horizontalAccuracy,
                  locationManager.location.speed,
                  dateString];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%lu", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *sUrl = [[NSUserDefaults standardUserDefaults] stringForKey:@"serviceUrl"];
NSString *swoclString = [NSString stringWithFormat:@"%@/saveLocation.php", sUrl];
[request setURL:[NSURL URLWithString:swoclString]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if(conn) {
    NSLog(@"Location Save Successfully");
} else {
    NSLog(@"Location Save Error");
}

我可以在服务器端接收数据。在iOS端,我可以看到日志"位置保存成功"。

如何在没有implementing other methods的情况下从服务器收到回复?

2 个答案:

答案 0 :(得分:1)

使用NSURLSession而不是NSURLConnection将数据发布到服务器。以下是如何发布JSON的示例。

NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:nil delegateQueue:nil];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"<YOUR-URL-STRING>"] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:120.0];

[request setHTTPMethod:@"POST"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];

 NSError *error;
 NSData *postData = [NSJSONSerialization dataWithJSONObject:<YOUR_JSON_DATA> options:NSJSONWritingPrettyPrinted error:&error];

NSString *tmp = [[NSString alloc]initWithData:postData encoding:NSUTF8StringEncoding];

[request setHTTPBody:postData];

NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
        NSHTTPURLResponse *resp = (NSHTTPURLResponse *) response;
        NSLog(@"%li",(long)resp.statusCode);
        if(resp.statusCode==200){
            NSMutableArray *result = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
    }];`

该块用于返回服务器的响应。例如,HTTP状态代码和响应数据。如果使用json,则可以使用NSJSONSerialization类转换数据。

答案 1 :(得分:1)

If you are using latest ios coding standards you must have to use URLSession object to send any request to the API calls because DEPRECATED: The NSURLConnection class should no longer be used. NSURLSession is the replacement for NSURLConnection. But still, if you want to continue with an old procedure, there are three ways to send API request.

P1:

-(void)procedure1{
    NSURLRequest *requestObject = nil; /** replace with your request object **/
    NSURLResponse *serverResponse = nil;
    NSError *connectError = nil;

    /* thread bloker request */
    NSData *responseData = [NSURLConnection sendSynchronousRequest:requestObject returningResponse:&serverResponse error:&connectError];
    if (connectError == nil) {
        //parse server response data (i.e, json or xml)
    }else{
        /* handle connection error */
    }
}

P2:

-(void)procedure2{
    NSURLRequest *requestObject = nil; /** replace with your request object **/
    /* thread free request */
    [NSURLConnection sendAsynchronousRequest:requestObject queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil) {
            //parse server response data (i.e, json or xml)
        }else{
            /* handle connection error */
        }
    }];
}

P3: the last one is a bit different than the other two,

@interface TestViewController ()<NSURLConnectionDelegate>
@property (nonatomic, retain) NSMutableData* responseData;
@end



-(void)procedure3{
    NSURLRequest *requestObject = nil; /** replace with your request object **/
    NSURLConnection *connectionObject = [NSURLConnection connectionWithRequest:requestObject delegate:self];
    [connectionObject start];
}

here in this procedure you are required to invoke NSURLConnectionDelegate methods

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [self.responseData setLength:0];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.responseData appendData:data];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString* responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];
    connection = nil;
}