【发布时间】:2016-06-14 05:18:52
【问题描述】:
在目标 C 中点击 https url 时遇到一些问题。这是我的代码。
- (void)viewDidLoad {
NSString *urlString = [NSString stringWithFormat:@"MY URL",uid];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:urlString]];
[request setHTTPShouldHandleCookies:YES];
[request setHTTPMethod:@"GET"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
NSUInteger responseStatusCode = [httpResponse statusCode];
_responseData = [[NSMutableData alloc] init];
[self.responseData setLength:0];
NSLog(@"connection");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
NSLog(@"_responseData%@",_responseData);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError *jError;
NSArray *myApps= [NSJSONSerialization JSONObjectWithData:_responseData options:NSJSONReadingAllowFragments error:&jError];
NSLog(@"jError:%@",jError);
}
当我在模拟器中运行应用程序时,有时会获得 myApps 值。 但是大部分时间都没有得到响应。那时我能够看到 _responseData 和 myApps 的值为空。像这样获取 responseData
_responseData
像 this.myApps 这样的错误是空的
jError:Error Domain=NSCocoaErrorDomain Code=3840 "周围的值无效 字符 0。” UserInfo={NSDebugDescription=无效值 字符 0.}
当我收到此错误时,我尝试在浏览器中点击 URL,却在浏览器中得到响应。 所以我再次清理并运行应用程序,仍然面临同样的问题。 但是,如果更改模拟器,例如在 iPhone 6s 中运行并出现错误,现在更改为 iPhone 6,而不是得到响应。
谁能帮帮我。
【问题讨论】:
-
在
connectionDidFinishLoading:中,将_responseData转换为NSString,看看你有什么。 -
我试过 NSString* newStr = [[NSString alloc] initWithData:_responseData encoding:NSUTF8StringEncoding]; .但是我得到了 标签格式的响应,例如
标签: ios objective-c json nsurlconnection