1

I have a media player app that I'm working on, and I am sending an Alamofire request to obtain an URL in the form of a string... when I receive the response I do properly receive it as a string, but when I try to convert it into a NSURL, I keep getting nil.

The request is:

  Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
        .validate(statusCode: 200..<300)
        .responseString(encoding: NSUTF8StringEncoding)  { response in
            print("Response: \(response)")
            print("Response String: \(response.result.value!)")
            self.URLToPlay = response.result.value!
    }

My URLString is a String, my URLToPlay is also a String. The command I use to convert it to NSURL is

  let streamingURL = NSURL(string: self.URLToPlay) 

I get a valid URL-looking string in URLToPlay, in fact if I copy/paste that received string unto a browser, I am able to play the media... but when I use it to convert to NSURL, my app crashes (due to streamingURL being nil).

Now I believe this has something to do with the request being asynchronous, but I'm wondering if anyone has any idea of how to get this working?

I would greatly appreciate your help.

Edited to use a completion handler:

  func connectToServer() {
    print("Connecting...")

    finishLoad { theUrl in

        let urlString = theUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
        let streamingURL = NSURL(string: urlString!)

  // do what i need to do

    }

    isConnectedToServer = true
    print("Connected...")
}
func finishLoad(complete: (urlToBePlayed: String) -> ()) {
    var aVar: String!
    Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
        .validate(statusCode: 200..<300)
        .responseString(encoding: NSUTF8StringEncoding)  { response in
            aVar = response.result.value!
            complete(urlToBePlayed: aVar)
    }
}
Agustin
  • 166
  • 1
  • 11

1 Answers1

1

This is an Async process and no matter where you use URLToPlay OUTSIDE the .GET function of Alamofire, it is going to return nil because it will be nil as the process is async and the variable is still not updated at all. You can wrap this up in a completion handler and use like so:

func finishLoad(complete: (urlToBePlayed: String) -> ()) {
let aVar: String!
 Alamofire.request(.GET, URLString, parameters: ["foo": "bar"])
        .validate(statusCode: 200..<300)
        .responseString(encoding: NSUTF8StringEncoding)  { response in
            print("Response: \(response)")
            print("Response String: \(response.result.value!)")
            aVar = response.result.value!             
            complete(urlToBePlayed: aVar)
    }
}

Now call and use it like so:

finishLoad { theUrl in
let urlString = theUrl.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQ‌​ueryAllowedCharacter‌​Set())  //Fixes the deprecated error.
var convertToURL = NSURL(string: urlString)!     
 print(convertToURL)

//here you do what you want
}
Mtoklitz113
  • 3,828
  • 3
  • 21
  • 40
  • Thank you for taking the time to answer!, I had a sneaky suspicion that I needed to use a "completion handler"... I was just thinking I had to use NSNotifications and observers... but this seems like a good Idea... I will test this in a while and get back to you – Agustin Aug 19 '16 at 01:20
  • I have added to my original post your example, and I still get an error found nil right after I try to convert a string to NSURL... – Agustin Aug 19 '16 at 01:33
  • `print(theUrl)` after `theUrl in` and see if it shows anything? – Mtoklitz113 Aug 19 '16 at 01:35
  • yep I did that, i do get a valid string... the error comes after the following lines of code where I say: let streamingURL = NSURL(string: theUrl) then I try to use it by saying: self.playerItem = AVPlayerItem(URL: streamingURL!) ... and that's when it crashes, because It's trying to use streamingURL but it's nil... so the conversion of "theUrl" to NSURL is what's giving me nil – Agustin Aug 19 '16 at 01:38
  • I think this will work, I saw it previously in one of my searches, but the problem is that I get a warning saying it's deprecated... but for now, yes it works I get a valid URL to use with AVPlayerItem. Thanks a lot! – Agustin Aug 19 '16 at 01:55
  • Fixed the deprecated warning. Please accept the answer if it works for you. :) – Mtoklitz113 Aug 19 '16 at 01:58
  • I get the following error: Type 'NSCharacterSet' has no member 'URLQ‌​ueryAllowedCharacter‌​Set' – Agustin Aug 19 '16 at 01:59
  • What version of swift are you using? – Mtoklitz113 Aug 19 '16 at 02:01
  • The one that comes with Xcode 7.3, but I found out I just needed to add this: NSCharacterSet, accepting your answer! Thanks again! – Agustin Aug 19 '16 at 02:02
  • I'm hoping I can add one last question which is still part of the issue, when the convertToURL does return a valid URL but, it adds a "%0a" at the end, would you know how to remove this or how to prevent this? Thanks! – Agustin Aug 19 '16 at 02:11