这是我的第一篇文章,我想首先感谢stackoverflow的许多贡献者,他们永远不会知道在过去的几天里,在我努力完成我的第一个iOS应用程序的过程中,他们帮了我多少忙。我感谢他们,感谢这个网站给了他们一个发帖的地方。为了“还清”一些债务,我希望这能帮助其他人,因为我已经得到了帮助……
因此,我的应用程序使用GKPeerPickerController连接到第二台设备。一旦连接起来,这些设备就可以互相发送文本消息。接收方将消息显示在UIAlertView中。一切都运行得很好。
然后,我决定尝试使用位置,并添加代码来获取当前位置。我将其转换为经度、度、分和秒,并将它们放入一个NSString中。我在我的故事板上添加了一个名为“发送位置”的按钮,当点击时,它会将位置发送给连接的对等体。这就是我遇到问题的地方。
btnSendLocation使用NSString调用sendPacket。sendPacket将字符串转换为NSData并调用失败的sendDataToAllPeers。当我学会如何捕获错误时,它是“-sendDataToAllPeers:withDataMode: error :的无效参数:”。为什么会出现这个错误?我还有另外两个方法,它们也调用sendPacket并正常工作。
-(IBAction)btnSendLocation: (id)sender
{
// Put latitude, longitude into string, then convert to NSData for sending
NSMutableString *tmp = [[NSMutableString alloc] initWithString:@"Latitude: "];
// Build the location string to send
[tmp appendString:slatitude];
// …code for longitude
strToSend = [tmp copy];
bool sentPkt = false;
sentPkt = [self sendPacket:strToSend failedWithError:nil];
}
- (bool)sendPacket: (NSString *)strToSend failedWithError: (NSError *)error
{
bool sendPktOK = false;
packet = [strToSend dataUsingEncoding:NSASCIIStringEncoding];
// Send the packet.
sendPktOK = [self.currentSession sendDataToAllPeers:packet
withDataMode:GKSendDataReliable error:&error];
// If there was an error, log it.
if (!sendPktOK) {
NSLog(@"Error Domain: %@", [error domain]);
NSLog(@"Error Descr: %@", [error localizedDescription]);
NSLog(@"Error Code: %@", [error code]);
return NO;
}
return YES;
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
// Location default is decimal degrees notation; convert to deg-min-secs
int degrees = newLocation.coordinate.latitude;
double decimalPart = fabs(newLocation.coordinate.latitude - degrees);
int minutes = decimalPart * 60;
double seconds = decimalPart * 3600 - minutes * 60;
NSString slatitude = [NSString stringWithFormat:@"%d° %d' %1.1f\"",
degrees, minutes, seconds];
// rest of code...
}发布于 2012-04-09 04:32:00
我能够做更多的测试,并找到了答案。问题不在sendDataToAllPeers中,而是在NSString (strToSend)到NSData的转换过程中:
packet = [strToSend dataUsingEncoding:NSASCIIStringEncoding];具体来说,它是度符号字符(小圆圈,ASCII176)。NSASCIIStringEncoding只包含最多127个ASCII字符,这在NSString.h (Foundation.framework)的注释中得到了确认。我确信有一种更快的方法来发现问题,但我还不太了解Objective-C或Xcode的调试工具。
https://stackoverflow.com/questions/10060599
复制相似问题