方法早退,不完成

时间:2017-07-13 08:57:26

标签: c# xamarin.ios xamarin.forms

此方法永远不会超过foreach循环。无论我在它之后放置什么,都不会跑。即使书籍对象中没有联系对象,也不应该只跳过剩下的代码。这是用于我正在处理的应用程序中的联系人选择器,有关这里发生了什么的任何想法?感谢

public class UserContactService : IUserContactService
{
    public List<Contact> GetContacts()
    {
        List<Contact> contacts = new List<Contact>();
        var book = new Xamarin.Contacts.AddressBook();
        Console.WriteLine("Before loop");
        foreach (Contact c in book)
        {
            contacts.Add(c);
        }
        Console.WriteLine(DateTime.Now);
        return contacts;
    }
}

1 个答案:

答案 0 :(得分:4)

使用Xamarin,您需要先检查用户是否已授予访问联系簿的权限,否则您的foreach将会出错(因为本书永远不会包含联系人)。

要获得应用用户的权限,您也可以在Xamarin中执行此操作:

if (!await book.RequestPermission()) {
    Console.WriteLine("Permission denied by user or manifest");
    return;
}

我还将你的foreach包装在try / catch中以获取其他错误信息等:

try {      
    foreach (Contact c in book)
    {
        contacts.Add(c);
    }
} catch (Exception ex) {
    Console.WriteLine(ex);
}

有关Xmarin Mobile的更多信息,请访问:https://components.xamarin.com/view/xamarin.mobile