2017-01-12 5 views
2

오히려 Xamarin Forms/Visual Studio에 익숙하지 않지만 현재 나의 현재 상황입니다. Android, iOS 및 Windows Phone 하위 프로젝트가있는 Visual Studio에 Xamarin Forms 프로젝트가 있습니다. 당신이 Debug.WriteLine() 년대에서 볼 수 있듯이Xamarin Forms Visual Studio 2015 iOS에서 작동하지 않는 HttpClient 요청

public async Task<Tuple<bool, object>> Login(LoginCredentials credentials) 
    { 
     var loginUrl = apiUrl + "/login"; 
     var json = JsonConvert.SerializeObject(credentials); 
     var content = new StringContent(json, Encoding.UTF8, "application/json"); 
     try 
     { 
      Debug.WriteLine("start of try block"); 
      HttpResponseMessage response = await client.PostAsync(loginUrl, content); 
      Debug.WriteLine("this will not print on iOS"); 
      string bodyStr = await response.Content.ReadAsStringAsync(); 
      if (response.IsSuccessStatusCode) 
      { 
       // code that does stuff with successful response 
      } else 
      { 
       // code that does stuff with bad response 
      } 
     } catch (Exception e) 
     { 
      Debug.WriteLine(e); 
      return new Tuple<bool, object>(false, e.Message); 
     } 
    } 

, 예외가 라인에 발생합니다 :

HttpResponseMessage response = await client.PostAsync(loginUrl, content); 

예외는 그러나 System.NullReferenceException: Object reference not set to an instance of an object

이며,이 나는 다음과 같은 기능 로그인이 예외는 iOS에서만 발생합니다. Android와 Windows Phone 모두이 요청을 성공적으로 수행 할 수 있습니다.

내 첫 번째 가정은 입니다. Apple의 ATS은 내 서버가 https를 사용하지 않는 dev 인스턴스이기 때문에 의미가 있습니다. 그래서 iOS 프로젝트의 Info.plist에 붙여 넣은

<key>NSAppTransportSecurity</key> 
<dict> 
    <key>NSAllowsArbitraryLoads</key> 
    <true/> 
</dict> 

에 붙여 넣었습니다. 아직도 운이 없다.

다른 곳에서도 Windows의 Visual Studio와 Mac의 Xamarin이 내가 최신 버전인지 확인하는 질문을 읽었습니다.

또한 apiUrlhttp://localhost입니다. 내가 확인한 로컬 네트워크 (Mac 및 iOS 시뮬레이터는 다른 컴퓨터에서 실행 중이므로)에서 IP를 사용하고 있습니다.

이 시점에서 추측해야만한다면 ATS 설정이 제대로 설정되지 않았지만 여전히이를 확인할 수 없었습니다. 여기에서 어디로 가야할지 모르겠다. 계속 디버그하고 업데이트를 추가하겠습니다 만 도움이 될 것입니다.

업데이트 : 아이폰 OS를 실행하는 경우

Oleg Bogdanov에 의해 제안

, 내 클라이언트 인스턴스가 제대로 만 인스턴스화되지 않습니다.

디버깅 아이폰 OS : iOS HttpClient Debug

하는 안드로이드 디버깅 : Android HttpClient Debug

이제 작업이 iOS에서 발생하는 이유를 파악된다. 다음은 client 초기화 코드입니다. 나는 그것이 현재있는 곳과 그것이 논평 된 곳을 모두 시도했다.

public class API 
{ 
    public HttpClient client = new HttpClient(); 
    public string apiUrl = "http://myApiUrl"; 

    public API() 
    { 
     //this.client = new HttpClient(); 
    } 

    public async Task<Tuple<bool, object>> Login(LoginCredentials credentials) 
    { 
     // login function code 
    } 
} 

새로운 디버깅이있을 때이 디버깅을 계속하고 다른 업데이트를 게시합니다. 늘 그렇듯이, 어떤 도움도 크게 감사합니다.

+0

요청을 '게시'하려고 할 때 '클라이언트'가 인스턴스화 된 것이 확실합니까? – Demitrian

+0

예. 어떤 이유로 든 안드로이드와 윈도우에있을 것이고 iOS에 있지 않을 경우 – DerFlickschter

+1

null 인 클라이언트 인스턴스가 무엇인지 확인하십시오. –

답변

1

내가 솔루션 here을 찾았을 내 POC

을 위해 노력하고 다음 코드를 확인하시기 바랍니다.

NuGet Install-Package Microsoft.Net.Http을 Portable 프로젝트에 연결했는데 현재 작동 중입니다.

0

ATS에는 아무 것도 없다고 생각합니다. localhost공유 로컬 서버을 사용하여 하나의 POC를 만들었습니다.POST 요청

try 
    { 
     HttpClient client = new HttpClient(); 
     var uri = new Uri("http://localhost/RegisterDevice"); 
     string data = "{\"username\": \"ADMIN\",\"password\": \"123\"}"; 
     var content = new StringContent(data, Encoding.UTF8, "application/json"); 

     HttpResponseMessage response = null; 
     response = await client.PostAsync(uri, content); 
     Util.HideLoading(); 
     if (response.IsSuccessStatusCode) 
     { 
      System.Diagnostics.Debug.WriteLine(@"Success"); 
     } 
     else 
     { 
      System.Diagnostics.Debug.WriteLine(@"Fail");     
     } 
    } 
    catch (Exception ex) 
    { 

    } 
관련 문제