2013-02-01 204 views
1

我想在NSUserDefaults中將電話號碼存儲爲NSString。出於某種原因,下面的代碼不起作用。如果我不使用變量,代碼將起作用,但我無法使其工作。有沒有人有任何想法爲什麼?iOS從NSUserDefaults撥打電話號碼

NSString *savedPhone = [[NSUserDefaults standardUserDefaults] 
         stringForKey:@"savedPhone"]; 

NSString *callNumber = [NSString stringWithFormat:@"%@%@",@"tel://",savedPhone]; 

NSURL *myURL = [NSURL URLWithString:callNumber]; 
[[UIApplication sharedApplication] openURL:myURL]; 

請讓我知道,如果任何人有任何想法。謝謝!

回答

0

你可以用下面的代碼實現:

NSUserDefaults *objUserDefaults = [NSUserDefaults standardUserDefaults]; 
NSString *savedPhone = [objUserDefaults objectForKey:@"savedPhone"]; 
[self callNumber:savedPhone]; 

然後添加以下功能:

-(void)callNumber:(NSString *)pstrContactNo 
{ 
    NSString *strDeviceModel = [UIDevice currentDevice].model; 
    if(![strDeviceModel isEqualToString:@"iPhone"]) 
    { 
      UIAlertView *objAlertMsg = [[UIAlertView alloc] initWithTitle:@"" 
                 message:@"Calling is not supported in this device." 
                 delegate:nil 
              cancelButtonTitle:@"OK" 
              otherButtonTitles:nil]; 
     [objAlertMsg show]; 
     [objAlertMsg release]; 
    } 
    else 
    { 
     pstrContactNo = [NSString stringWithFormat:@"tel:%@",pstrContactNo]; 
     NSString *strDialedContact = [pstrContactNo stringByReplacingOccurrencesOfString:@" " withString:@""]; 
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:strDialedContact]]; 
    } 
} 

這將解決您的問題。

乾杯!

+1

見@Oleg後,將導航回到您的應用程序回答,你應該刪除''//在'電話:'方案。此外,如果設備支持'tel:'方案,然後檢查設備型號是否是iPhone,則更好。只需使用'[[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@「tel:」]' – rckoenes

+0

@rckoenes:答案不被接受。那麼爲什麼你有這個答案?這也是測試代碼。不知道。 –

+0

我沒有downvote你的答案。我只是想告訴你,你的回答有一些錯誤。 – rckoenes

1

更改您的網址格式(刪除//

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"tel:2135554321"]]; 
0

更改callNumber這樣的: 的NSString * callNumber = [的NSString stringWithFormat:@ 「電話:%@」,savedPhone]。

0
NSString *number = YOUR-NUMBER;  
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"telprompt:%@",number]]; 

[[UIApplication sharedApplication] openURL:url]; 

嘗試使用此代碼,呼完