我是 iOS 应用程序开发的新手。我在登录页面有一个问题。 有时登录需要很长时间。我使用此代码发送或接收来自http服务器的请求。
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonData1
options:0 // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (!jsonData) {
NSLog(@"Got an error: %@", error);
} else {
jsonString= [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"converted json string is %@",jsonString);
}
NSData *postData = [[[NSString alloc] initWithFormat:@"method=methodName&email=%@&password=%@", user_name, pass_word] dataUsingEncoding:NSASCIIStringEncoding ];
NSString *postLength = [NSString stringWithFormat:@"%ld",[postData length]];
jsonData=[jsonString dataUsingEncoding:NSASCIIStringEncoding];
NSLog(@"the final passing json data is %@",jsonData);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http:urladdress"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json" forHTTPHeaderField:@"\"Accept\""];
[request setValue:@"application/json" forHTTPHeaderField:@"\"Content-Type\""];
[request setValue:postLength forHTTPHeaderField:@"\"Content-Length\""];
[request setValue:@"application/x-www-form-urlencoded;" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:jsonData];
NSError *requestError = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&requestError];
//if communication was successful
if ([response statusCode] >= 200 && [response statusCode] < 300) {
NSError *serializeError = nil;
NSString* newStr = [NSString stringWithString :[urlData bytes]];
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingAllowFragments
error:&serializeError];
NSLog(@"recdata %@",jsonData);
}
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
NSLog(@"theConnection is succesful");
self.receivedData = [NSMutableData data];
}
[connection start];
[self readFromDataBase];
if (dataCheck==true) {
[self checkPassword];
}
有没有办法更快地登录。?
答案 0 :(得分:2)
由于您的服务器或连接质量,可能连接速度很慢。
你尝试过异步吗?在等待回复时,它不会冻结您的应用
Asynchronous NSURLConnection Scheme Tutorial
对于您的程序,请替换sendSync方法:
NSData *urlData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response
error:&requestError];
通过sendAsync方法:
NSOperationQueue *mainQueue = [[NSOperationQueue alloc] init];
[mainQueue setMaxConcurrentOperationCount:5];
[NSURLConnection sendAsynchronousRequest:request queue:mainQueue completionHandler:^(NSURLResponse *response, NSData *urlData, NSError *requestError) {
// doing somethings ...
// if communication was successful ...
}];